1. 程式人生 > >偽陣列及其轉化

偽陣列及其轉化

在之前的筆試題中,遇到了一道題目:什麼是偽陣列?如何將偽陣列轉化為標準陣列?

▍什麼是偽陣列?

一般符合以下三個條件的稱之為偽陣列:

1、具有陣列的length屬性;

2、按照索引方式儲存資料(可以通過“[]”找到相應的項);

3、不具有陣列的一些方法(push、pop等)。

參考示例:

var obj3 = { length: 0 };
var obj4 = { 0: '888', length: 1 };
var obj5 = { 99: 'abc', length: 100 };

▍偽陣列如何轉化成標準陣列?

1、使用Array.prototype.slice.call();

console.log(Array.prototype.slice.call({
	0: "yeluosen",
	1: 12,
	2: true,
	length: 3
}));
// ["yeluosen", 12, true]

2、使用[].slice.call();

console.log([].slice.call({
	0: "yeluosen",
	1: 12,
	2: true,
	length: 3
}));
// ["yeluosen", 12, true]

3、使用ES6中Array.from方法;

console.log(Array.from({
	0: "葉落森",
	1: 18,
	2: 2014,
	3: "北京郵電大學",
	length: 4
}));
// ["葉落森", 18, 2014, "北京郵電大學"]