谁能解释一下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:
根据该键定义,任何不是此索引的属性名称都只是常规属性名称(如键顺序所示)(数组索引按顺序;其他属性按插入顺序):
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"]