任何人都可以解释这种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"
Run Code Online (Sandbox Code Playgroud)
我用Number.MIN_VALUE尝试了这个.
有谁知道这背后的原因?
Number.MAX_VALUE不是有效的数组索引.根据规格:
的整数指数是一个字符串值属性密钥是一个规范的数字串(见7.1.16),并且其数字值是0或正整数2≤ 53 -1.数组索引是整数索引,其数值i在+0≤i<2 32 -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"]
Run Code Online (Sandbox Code Playgroud)