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

查看:196
本文介绍了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,但它们与[]运算符的行为不同。为什么?

Both objects inherits Array.prototype, but they behave differently with the [] operator. Why?

推荐答案

在第一种情况下,您创建一个维护长度的数组对象属性。

In the first case you create an array object that maintains the length property when you access a integer, non-negative property (index).

在第二种情况下,您创建了一个常规对象继承 Array 原型。在该对象上使用 [] 与任何对象相同,只需在其上设置常规属性。

In the second case you created a regular object that inherits the Array prototype. 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.

ECMAScript 5语言规范描述长度的方式保存在第15.4节中。

The ECMAScript 5 Language Spec describes how length is maintained in section 15.4.


数组对象对某类属性
名称给予特殊处理。属性名称​​ P (以String值的形式)是数组索引当且仅当ToString(ToUint32( P ))是等于 P
ToUint32( P )不等于2 ^(32-1)。

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;

这篇关于new Array()vs Object.create(Array.prototype)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆