今天再执行以下代码段的时候,遇到了一个报错".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循环,发现能正常运行,这点很有意思。

相关文章:

  • 2021-06-19
  • 2021-10-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-25
  • 2021-12-11
  • 2022-01-23
相关资源
相似解决方案