在我们开发过程中很多情况下能获取到类似数组的对象,有时候我们需要对这类数组进行操作(去调用数组的方法)此时我们就需要将类数组转换为真正的数组,一下提供几种转换方法
1.使用es6中的 Array.from()方法转换
let list = {
0 : 1,
1 : 2,
2 : 3,
length : 3
}
let arr = Array.from(list);
console.log(arr); // [1, 2, 3]
2.使用es6+ 扩展运算符
// HTMLcontrion 伪数组集合 NodeList 伪数组集合
let arr = [...HTMLcontrion]
3.使用apply或者call
let list = {
0 : 1,
1 : 2,
2 : 3,
length : 3
}
// apply
let arr = [].concat.apply([],list)
// call
let arr = Array.prototype.slice.call(list)
console.log(arr)
4.遍历类数组,将类数组元素依次放入一个新数组
let list = {
0 : 1,
1 : 2,
2 : 3,
length : 3
}
let arr = [];
for(let item of list ){ arr.push(item)
}
console.log(arr); // [1,2,3]