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); });