類數組對象轉換為數組的六種方法


xxx.forEach is not a function(DOM集合--類數組對象轉化為數組)

原生js獲取的DOM集合是一個類數組對象,所以不能直接利用數組的方法(例如:forEach,map等),需要轉換為數組后,才能用數組的方法。

6種解決辦法(假如hdList是一個DOM集合)

(1)Array.from()方法

//將hdList用Array.from()方法轉換為數組,並用list變量接收
let list = Array.from(hdList);

(2)用Array.prototype.slice.call(elems)方法轉化為數組

//hdList轉化為數組並用list變量接收
let list = Array.prototype.slice.call(hdList);
//添加點擊事件
list.forEach((current,index) => {
    current.addEventListener('click',() => {
        animationFn(index);
    },false);
});

(3)用[ ...elems ]方法轉化為數組

let list = [...hdList];//用[ ...elems ]方法轉化為數組並用list接收

(4)用Array.prototype.forEach.call(elem,callback)方法

//直接對hdList集合進行循環或者map等
Array.prototype.forEach.call(hdList,function(){
//...
})
Array.prototype.map.call(hdList,function(){
//...
})

(5)用Array.prototype.forEach.apply(elem,[callback])方法

//添加點擊事件
Array.prototype.forEach.apply(hdList,[(current,index) => {
    current.addEventListener('click',() => {
        animationFn(index);
    },false);
}]);

(6)用bind方法

//添加點擊事件
Array.prototype.forEach.bind(hdList)((current,index) => {
    current.addEventListener('click',() => {
        animationFn(index);
    },false);
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM