gpt4 book ai didi

javascript - 为什么 JavaScript 中的数组显示错误的长度

转载 作者:搜寻专家 更新时间:2023-11-01 05:24:43 24 4
gpt4 key购买 nike

我正在学习 Javascript。作为学习的一部分,我遇到了以下情况,我希望 a1.length(代码的最后一行)显示 201,但它显示 101,任何想法?

var a1 = new Array();

for (var i = -100; i<=100; i++)
a1[i] = i;

for (var i in a1)
{
document.write(i + "=" + a1[i])
document.write("<br>");
}

document.write(a1.length);

最佳答案

我会将我的原始评论转换为更详尽的答案。

.length 中计算的数组索引从 0 开始。负索引被认为是对象的属性,而不是数组值。正如您从下面的 ECMAScript 规范中看到的那样,数组索引本质上只是特定类型的属性值,并进行了一些特殊处理。

来自 ECMAScript spec 的第 15.4 节:

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 2^32. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 2^32 . The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. 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; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.


另外,你永远不应该 "iterate" arrays with a for-in-loop :

for (var i in a1)

迭代 a1 的所有可枚举属性,其中将包括所有数组索引,但也可能包括其他属性。如果您只想使用 for 循环迭代数组元素,您应该使用其他形式:

for (var i = 0, len = a1.length; i < len; i++) 

打字稍微多一些,但安全得多。

或者,在更现代的浏览器中,您可以使用 .forEach() method .

关于javascript - 为什么 JavaScript 中的数组显示错误的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13333000/

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