天真的困惑:
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
原型(prototype)的常规对象。在该对象上使用 []
与任何对象相同,只需在其上设置常规属性即可。
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 语言规范描述了如何在 section 15.4 中维护 length
.
Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^(32−1).
[...]
Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index;
关于javascript - new Array() 与 Object.create(Array.prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22022058/