gpt4 book ai didi

javascript - 学习 Array.prototype 并计算其长度

转载 作者:行者123 更新时间:2023-12-04 11:59:08 26 4
gpt4 key购买 nike

第一:最近才知道Array.prototype本身就是一个array([])。但是很神奇的是它不是Array对象的实例。这怎么可能?这是什么原因?

第二:Array.prototype 有很多属性,但是当你登录时,即 console.log(Array.prototype.length) ,输出是'0'。这是什么原因?我也试过,结果一样

var x=[];
x['a']="b";
x['b']="c";
console.log(x.length)//output:0

如果你能告诉我数组元素和属性的区别就太好了

最佳答案

I recently knew that Array.prototype is itself an array ([]).

你没看错,就是一个数组。规范在 §15.4.4, Properties of the Array Prototype Object 中说:

The Array prototype object is itself an array; its [[Class]] is "Array", and it has a length property (whose initial value is +0) and the special [[DefineOwnProperty]] internal method described in 15.4.5.1.


But an amazing thing is that it is not the instance of Array object. How is that possible? What is the reason for this?

如果您尝试了 Array.prototype instanceof Array,那么结果确实是 false。为什么?由于 instanceof 运算符的工作方式。它将对象的原型(prototype)与构造函数的 prototype 属性的值进行比较。
IE。在这种情况下它确实如此

Object.getPrototypeOf(Array.prototype) === Array.prototype

正如我们在这个比较中已经看到的那样,我们正在尝试测试 Array.prototype 是否是其自己的 原型(prototype),这是不可能的。规范同段还提到:

The value of the [[Prototype]] internal property of the Array prototype object is the standard built-in Object prototype object (15.2.4).

Object.getPrototypeOf(Array.prototype) === Object.prototypeObject.prototype !== Array.prototype。因此 instanceof 产生 false,但是 Array.prototype 仍然是一个数组。


Array.prototype has many properties but when u log i.e console.log(Array.prototype.length), the output is '0'.

0Array.prototype.length 的值在规范中定义(见上文)。

It would be great if u let me know the difference in element and property of an array

数组的元素 是一个属性,其属性名称是 32 位正整数(或 0)。 属性 是没有此类属性名称的任何其他属性。任何数组操作都不考虑这些。

规范在 §15.4, Array Objects 中提供了更精确的描述:

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 232−1. A property whose property name is an array index is also called an element.

所以你看,如果一个属性名被转换为一个无符号的 32 位整数(的字符串表示)并且仍然具有相同的值,那么它是一个数组索引并且关联的值是数组的一个元素。

规范连续

The value of the length property is numerically greater than the name of every property whose name is an array index;

我们刚刚了解到哪些属性名称被认为是数组索引,哪些属性名称可以转换为无符号整数。根据该定义,"a" 不是数组索引,因此

var x = [];
x['a'] = 42;

不改变length 属性。但是 "3" 是一个数组索引,所以

x["3"] = 42;

length 属性更改为 4

关于javascript - 学习 Array.prototype 并计算其长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17248437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com