Warm tip: This article is reproduced from stackoverflow.com, please click
arrays javascript

Javascript .map() is not a function

发布于 2020-03-31 22:59:37

I am new here (and new to JavaScript), so please excuse my super basic questions. I have a HTML page with different images that all share a class on it. By using getElementsByClassName, I get an array. I want to add an event listener to each of the cells in the array by using the .map() function.

This is what I have:

window.onload = function(){
var allImgs = document.getElementsByClassName("pft");

var newImgs = allImgs.map(
        function(arrayCell){
            return arrayCell.addEventListener("mouseover, functionName");
        }
    );
}; 

This keeps showing the error "allImgs.map is not a function" even when I change the inner function to something that doesn't include the event listener.

I have another version of this code where I just loop through the array cells within window.onload and add the event listener to each of them that way and it works. Why isn't the .map() function working? Can it not be used in window.onload?

Questioner
JSn00b
Viewed
17
flawyte 2017-11-13 21:23

getElementsByClassName() returns an HTMLCollection not an Array. You have to convert it into a JavaScript array first :

allImgs = Array.prototype.slice.call(allImgs);
// or
allImgs = [].slice.call(allImgs);
// or
allImgs = Array.from(allImgs);