索引为 Number.MAX_VALUE 的 Javascript 数组

标签 javascript arrays

谁能解释一下 javascript 数组的这种行为

//create an empty array
var arr=[];

//added an entry with index Number.MAX_VALUE
arr[Number.MAX_VALUE]="test"

//On printing the array, its showing as empty
arr
//[]

//even its length=0
arr.length
//0

//on accessing the same value its showing the correct value
arr[Number.MAX_VALUE]
//"test"

我已经用 Number.MIN_VALUE 试过了。

有人知道这背后的原因吗?

最佳答案

Number.MAX_VALUE 不是有效的数组索引。 According to the spec:

An integer index is a String-valued property key that is a canonical numeric String (see 7.1.16) and whose numeric value is either +0 or a positive integer ≤ 253-1. An array index is an integer index whose numeric value i is in the range +0 ≤ i < 232−1.

根据此定义,任何不是数组索引的属性名称都只是常规属性名称,正如您可以通过键顺序看到的那样(数组索引按顺序排列;其他属性按插入顺序排列):

var a = {};
a.prop = 'foo';
a[2 ** 32 - 2] = 'bar';
a[Number.MAX_VALUE] = 'baz';
console.log(Object.keys(a));
// ["4294967294", "prop", "1.7976931348623157e+308"]

关于索引为 Number.MAX_VALUE 的 Javascript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42744603/

相关文章:

javascript - 一旦我在数组上使用 array.prototype.map/filter ,是否可以将其转换回原始数组?

javascript - 无法访问数组中的对象,只能访问对象本身

javascript - 适用于现代浏览器的轻量级 JavaScript 库

javascript - React CSS 模块污染了全局命名空间

javascript - HTML5 文件 API 真的会改变用户的文件上传体验吗?

javascript - 对象 javascript 的条件

javascript - 替代使用 eval()

java - 转换到泛型导致 Java 中的 ArrayStoreException

javascript - 如何获得 SVG 文本元素的紧密边界框

c - 有多少种方法可以打印我们的整数数组?