javascript - 在数组的负索引中添加元素?

标签 javascript

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/

相关文章:

javascript - 从哪里开始我的 Firefox 书签扩展

javascript - 未提供调试 WebStorm

Javascript 在单击按钮时多次打开链接

javascript - ngPattern 绑定(bind)不起作用

javascript - 从 DOM 操作转向面向对象的 Javascript

Javascript 像素操作 : These aren't my colors

javascript - 将数字转换为 4 字节字符串

javascript - 将Float64Array转换为数组

javascript - 即使数据被捕获,我的输入也返回未定义。使用 CRUD js

javascript - 使用 doc.output() 的问题 - jsPDF