`document.getElementsByClassName` 的结果没有定义像 `map` 这样的数组方法,即使它是一个数组 [英] Result of `document.getElementsByClassName` doesn't have array methods like `map` defined, even though it is an array

查看:42
本文介绍了`document.getElementsByClassName` 的结果没有定义像 `map` 这样的数组方法,即使它是一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码来选择一些 div 并在它们上添加点击处理程序

I have the following bit of code to select some divs and add a click handler on them

var tiles = document.getElementsByClassName("tile");

tiles.map(function(tile, i){
    tile.addEventListener("click", function(e){
        console.log("click!");
    });
});

这会引发错误,因为 map 未定义,即使tiles 是一个数组.如果我制作这样的数组,则 map 工作正常:

This throws an error because map is not defined, even though tiles is an array. If I make an array like this, then map works fine:

var a = [1, 2, 3, 4];
a.map(/*whatever*/);

一种解决方法是像这样将地图附加到图块上:

A workaround is to attach map to tiles like this:

tiles.map = Array.prototype.map;

这很好用.我的问题是为什么 tiles 上没有定义地图?真的不是数组吗?

This works fine. My question is why doesn't tiles have map defined on it? Is it not really an array?

推荐答案

是的,它并不是真正的数组.这是一个类数组".

Right, it's not really an array. It's an "array-like".

不要将 map 附加到 tiles.就做

Don't attach map to tiles. Just do

Array.prototype.map.call(tiles, function...)

有些人可能会建议

Array.prototype.slice.call(tiles).map(function...

哪种归结为同一件事.有些人更喜欢写作

which sort of boils down to the same thing. There are those who prefer to write

[].slice.call(tiles).map(function...

这样可以节省几次按键操作.

which saves a few keystrokes.

当然,由于您并没有真正使用 map 来返回数组,因此您可以以老式的方式循环:

Of course, since you're not really using map to return an array, you could loop in the old-fashioned way:

for (var i = 0; i < tiles.length; i++) {
    tiles[i].addEventListener("click", function(e){
        console.log("click!");
    });
}

另请参阅 MDN 上的说明.尽管这里讨论的是 NodeList,但同样的原则也适用于 HTMLCollection,即 getElementsByClassName 返回的内容.

See also explanation at MDN. Although this discusses NodeList, the same principles apply to HTMLCollection, which is what getElementsByClassName returns.

在 ES6 中,我们有一些更简单的方法将 tiles 转换为数组,包括

In ES6, we have some easier ways to turn tiles into an array, including

[...tiles]
Array.from(tiles)

这篇关于`document.getElementsByClassName` 的结果没有定义像 `map` 这样的数组方法,即使它是一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆