Javascript中什么是伪数组?如何将伪数组转化成标准数组?

2025-10-22 13:43:55 联动专题

在js中,数组是特殊的对象,凡是对象有的性质,数组都有,数组表示有序数据的集合,而对象表示无序数据的集合。

那伪数组是什么呢,当然它也是对象,伪数组一般具有以下特点:

按索引方式存储数据;具有length属性;没有数组的push、shift、pop等方法;

obj={

"0":"dai",

"1":18,

length:2

}

function的arguments对象,还有getElementsByTagName、ele.childNodes等返回的NodeList对象,或者自定义的某些对象,这些都可以是伪数组。

伪数组转换为标准数组

1 使用Array.prototype.slice.call()或[].slice.call()

let arr1 = {

0:"hello",

1:12,

2:true,

length:3

}

let arr11 = Array.prototype.slice.call(arr1); //返回的是数组

let arr111 = [].slice.call(arr1);//同上

//["hello", 12, true]

2 使用ES6中Array.from方法

let arr2 = {

0:"hello",

1:12,

2:2013,

3:"大学",

length:4

}

Array.from(arr2);

//["hello", 12, 2013, "大学"]