.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循环,发现能正常运行,这点很有意思。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM