夜间模式CodeSnippetStyle:
日间模式CodeSnippetStyle:

0%


.map() is not a function【js报错】

今天再执行以下代码段的时候,遇到了一个报错".map() is not a function":

    card.addEventListener("click", function(e) {
        let cardListE = document.getElementsByClassName("card");
         cardListE.map(item => {
             console.log(item == this)
         })
    });

在StackOverflow上找到了解释,

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);
  • map 不能遍历HTMLCollection类型数据,必须先将HTMLCollection转换成array。
  • 我接着使用了for循环,发现能正常运行,这点很有意思。
posted @ 2020-08-12 16:49  暮冬有八  阅读(18319)  评论(0编辑  收藏  举报
BACK TO TOP

😀迷海无灯听船行。Github WeChat