JavaScript 数组中的负索引是否会影响数组长度?
在javascript中我定义了一个这样的数组
In javascript I define an array like this
var arr = [1,2,3];
我也可以
arr[-1] = 4;
现在如果我这样做
arr = undefined;
我还丢失了对 arr[-1] 处的值的引用.
I also lose the reference to the value at arr[-1].
所以对我来说,从逻辑上讲,arr[-1] 也是 arr 的一部分.
SO for me logically it seems like arr[-1] is also a part of arr.
但是当我执行以下操作时(没有将 arr 设置为 undefined)
But when I do following (without setting arr to undefined)
arr.length;
它返回3而不是4;
所以我的观点是如果数组可以用于负索引,这些负索引也应该是它们长度的一部分**.我不知道是我错了,还是我遗漏了一些关于数组的概念.
So my point is if the arrays can be used with negative indexes, these negative indexes should also be a part of their length**. I don't know may be I am wrong or I may be missing some concept about arrays.
所以对我来说,从逻辑上讲,arr[-1] 也是 arr 的一部分.
SO for me logically it seems like arr[-1] is also a part of arr.
是的,但不是你想的那样.
Yes it is, but not in the way you think it is.
您可以为数组分配任意属性(就像 JavaScript 中的任何其他对象一样),这就是您在 -1
处索引"数组并分配值时所做的.由于这不是数组的成员而只是一个任意属性,因此您不应期望 length
考虑该属性.
You can assign arbitrary properties to an array (just like any other Object in JavaScript), which is what you're doing when you "index" the array at -1
and assign a value. Since this is not a member of the array and just an arbitrary property, you should not expect length
to consider that property.
换句话说,下面的代码做了同样的事情:
In other words, the following code does the same thing:
var arr = [1, 2, 3];
arr.cookies = 4;
alert(arr.length) // 3;