1. 什么是伪数组
满足两个条件的对象就是类数组。
- 有length属性,最好加上push方法
- 属性要为索引属性
- 常见的有函数参数的
arguments对象等
- 常见的有函数参数的
{
"0": 1,
"2": 23,
length: 2
}
类数组并不能直接使用数组的方法,需要用call()或者apply()调用数组的方法。
类似于这样
let arrObj = {
0: 0,
1: 1,
2: 2,
length: 3
}
let res = Array.prototype.slice.call(arrObj,0)
console.log(res);
2. 伪数组转变成真数组
- from()
- 自定义方法
- slice
- 扩展运算符
-
Array.from()
let arrObj = { 0: 0, 1: 1, 2: 2, length: 3 } // 1. Array.form Array.from(arrObj) //[0,1,2] -
自定义方法
let arrObj = { 0: 0, 1: 1, 2: 2, length: 3 } let arr = [] for(let i=0;i<arrObj.length;i++){ arr.push(arrObj[i]) } console.log(arr); -
Array.prototype.slice.call(obj,0)
截取函数
let arrObj = { 0: 0, 1: 1, 2: 2, length: 3 } let res = Array.prototype.slice.call(arrObj,0) console.log(res); -
扩展运算符 ...
function test(){ console.log(arguments); console.log([...arguments]); //[1,2,4,6] } test(1,2,4,6)