arr = Array(10).fill(false)
arr[-2] = true
console.log(arr)
[false, false, false, false, false, false, false, false, false, false, -2: true]
console.log(arr.length) // 10
我很惊讶在数组的负索引中添加一个元素,在数组中添加了一个键值对。而且,数组的长度不增加吗?
最佳答案
从MDN Array.length中提取定义
The length property of an object which is an instance of type Array sets or returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
它仅从从0开始的索引一直到最高数值进行计数。因此,任何无效或否定的东西都将被忽略。因此,长度实际上并不是您在视觉上看到的元素的数量。
与
length
属性MDN的关系If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values). If the argument is any other number, a RangeError exception is thrown.
Arrays cannot use strings as element indexes (as in an associative array) but must use integers. Setting or accessing via non-integers using bracket notation (or dot notation) will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's object property collection. The array's object properties and list of array elements are separate, and the array's traversal and mutation operations cannot be applied to these named properties.
此处指示设置值和属性之间的差异。像其他任何对象一样,超出数组有效范围设置的任何内容都被视为属性
关于javascript - 在数组的负索引中添加元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58570277/