今天再執行以下代碼段的時候,遇到了一個報錯".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循環,發現能正常運行,這點很有意思。