.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