类数组对象转换为数组的六种⽅法
原⽣js获取的DOM集合是⼀个类数组对象,所以不能直接利⽤数组的⽅法(例如:forEach,map等),需要转换为数组后,才能⽤数组的⽅法。
6种解决办法(假如hdList是⼀个DOM集合)
数组类型字符串转数组(1)ES6语法 Array.from(arr)
//将hdList⽤Array.from()⽅法转换为数组,并⽤list变量接收
let list = Array.from(hdList);
(2)⽤Array.prototype.slice.call(elems)⽅法转化为数组或 [].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);
});

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。