Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
688 views
in Technique[技术] by (71.8m points)

javascript - Result of `document.getElementsByClassName` doesn't have array methods like `map` defined, even though it is an array

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Don't attach map to tiles. Just do

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

Some might suggest

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.

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

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...