例如,如果我这样做 [1000000]=1; 它会为 1000000 个元素使用内存还是只为这个元素使用内存?
最佳答案
在 ECMAScript 标准(§15.4)中,数组的唯一特殊之处在于 length
属性会自动更新(以及一堆特定于数组的原型(prototype)函数):
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 andToUint32(
P)
is not equal to 232−1.
...
Every Array object has alength
property whose value is always a nonnegative integer less than 232. The value of thelength
property is numerically greater than the name of every property whose name is an array index; ...
除此之外,数组只是一个对象,这意味着它可以被视为关联数组,although you shouldn't .
如今,JS 引擎应该检测数组是密集的还是非常稀疏的,并在内部使用线性数组或关联数组之间进行切换。在您的情况下,JS 引擎不会分配一百万个元素。
关于javascript - JavaScript 数组是关联的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2575833/