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

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

问题描述

我有code以下位来选择一些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!");
    });
});

这将抛出一个错误,因为地图没有定义,尽管瓦片是一个数组。
如果我做一个这样的数组,然后映射工作正常:

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;

这工作正常。
我的问题是,为什么不瓷砖的地图上如何界定?它是不是一个真正的数组?

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".

不要将地图瓷砖。只要做到

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

有些人可能会认为

Some might suggest

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

哪种类型的归结为同样的事情。还有那些谁preFER写

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.

当然,由于你没有真正使用地图返回一个数组,你可以循环在老式的方式:

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!");
    });
}

又见<一个href=\"https://developer.mozilla.org/en/docs/Web/API/NodeList#Why_can't_I_use_forEach_or_map_on_a_NodeList.3F\"相对=nofollow>在MDN 解释。虽然这种讨论节点列表,同样的原则也适用于的HTMLCollection ,这是 getElementsByClassName 的回报。

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

在ES6,我们有一些更简单的方法把瓷砖到一个数组,包括

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

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

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

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