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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…