简体   繁体   English

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

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

A naive confusion: 天真的困惑:

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

Both objects inherits Array.prototype, but they behave differently with the [] operator. 两个对象都继承了Array.prototype,但它们与[]运算符的行为不同。 Why? 为什么?

In the first case you create an array object that maintains the length property when you access a integer, non-negative property (index). 在第一种情况下,您创建一个数组对象,在访问整数非负属性(索引)时维护length属性。

In the second case you created a regular object that inherits the Array prototype. 在第二种情况下,您创建了一个继承Array原型的常规对象 Using [] on that object is the same as any object and simply sets regular properties on it. 在该对象上使用[]与任何对象相同,只需在其上设置常规属性即可。

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.

The ECMAScript 5 Language Spec describes how length is maintained in section 15.4 . ECMAScript 5语言规范描述了如何在第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). 当且仅当ToString(ToUint32( P ))等于P且ToUint32( P )不等于2 ^(32-1)时,属性名P (以String值的形式)是数组索引

[...] [...]

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; 具体来说,每当添加名称为数组索引的属性时,如果需要,将更改length属性,使其大于该数组索引的数值;

var arr1 = new Array(); is the proper way to instantiate an array. 是实例化数组的正确方法。 It is the same as using the array literal: var arr1 = []; 它与使用数组文字相同: var arr1 = [];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM