簡體   English   中英

new Array()vs Object.create(Array.prototype)

[英]new Array() vs Object.create(Array.prototype)

天真的困惑:

var arr1 = new Array();
var arr2 = Object.create(Array.prototype);
//Inserting elements in "both arrays"
arr1[0] =0;
arr1[9] =9;
arr2[0] =0;
arr2[9] =9;
arr1.push(10);
arr2.push(10);
console.log(arr1.length); // prints 11
console.log(arr2.length); // prints 1

兩個對象都繼承了Array.prototype,但它們與[]運算符的行為不同。 為什么?

在第一種情況下,您創建一個數組對象,在訪問整數非負屬性(索引)時維護length屬性。

在第二種情況下,您創建了一個繼承Array原型的常規對象 在該對象上使用[]與任何對象相同,只需在其上設置常規屬性即可。

var arr1 = new Array(); // or var arr1 = [];
arr1[0] = 0;
arr1['foo'] = 3;
// arr1 has a length of 1 because 0 is an array index and 'foo' is a regular property.

var arr2 = Object.create(Array.prototype);
arr2[0] = 0;
arr2['foo'] = 3;
// arr2 has a length of 0 because both 0 and 'foo' are regular properties.

ECMAScript 5語言規范描述了如何在第15.4節中維護length

數組對象對特定類的屬性名稱進行特殊處理。 當且僅當ToString(ToUint32( P ))等於P且ToUint32( P )不等於2 ^(32-1)時,屬性名P (以String值的形式)是數組索引

[...]

具體來說,每當添加名稱為數組索引的屬性時,如果需要,將更改length屬性,使其大於該數組索引的數值;

var arr1 = new Array(); 是實例化數組的正確方法。 它與使用數組文字相同: var arr1 = [];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM