javascript - new Array() 与 Object.create(Array.prototype)

标签 javascript

天真的困惑:

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/

相关文章:

javascript - 当名称包含 "["字符时,jQuery 按名称获取对象

javascript - 自动将SCORM数据发送到LMS

javascript - 将文本输入的值与默认值进行比较

javascript - 滚动到某个位置时如何更改导航栏颜色?

javascript - 带有 FrameSet 的 Tinymce 不工作?

javascript - 为变量分配一个随机值

javascript - express 不会在 Linux 上获取某些图像。在 Windows 上工作正常

javascript - 在浏览器中查看 JSON 文件

asp-classic - 为 ServerXMLHTTP 请求设置超时

c# - 如何在 .js 文件中嵌入 Razor C# 代码?