谁能解释一下 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/