类数组转化为真正的数组

引言

开发过程中,有很多时候获取到的是类似数组的对象。比如元素的集合(elementcollection,nodeList,以及今天开发时发现classList也是类数组)。有时我们需要类数组去调用数组的方法,怎么办?

办法一

遍历类数组,将类数组里面的元素依次放入一个新的数组

  1. 类数组本身虽然不是数组,但是有interator接口,所以可遍历。(interator指可遍历、可迭代)
let foo = {
    0 : 1,
    1 : 2,
    2 : 3,
    length : 3
}

let arr = [];

for(let item of foo){
    arr.push(item)
}

办法二

使用 es6 中 Array.from()方法转换

let foo = {
    0 : 1,
    1 : 2,
    2 : 3,
    length : 3
}
let arr = Array.from(foo)

办法三

使用 apply 和 call
apply方法的第二个参数是数组,也可以是类数组,在调用的时候会将第二个参数依次展开。

let foo = {
    0 : 1,
    1 : 2,
    2 : 3,
    length : 3
}
// apply
let arr = [].concat.apply([],foo)
// call
let arr = Array.prototype.slice.call(foo)
console.log(arr)

猜你喜欢

转载自www.cnblogs.com/ifon/p/11409871.html