var person = [];
person.name = "Mr. White";
person.job= "Engineer";
person.push(5);
person.length的答案是什么,为什么?
数组在其.length
属性方面具有某些特殊行为。正如the specification描述的那样:
每个数组对象都有一个不可配置的“长度”属性,其值始终是一个小于232的非负整数。“长度”属性的值在数值上大于每个其名称为数组的属性的名称索引;每当创建或更改Array对象的自身属性时,都会根据需要调整其他属性以保持该不变性。具体来说,每当添加自己的名称为数组索引的属性时,“ length”属性的值就会更改]
“数组索引”是0到2 ** 32 - 1
之间的整数。
在person
数组的属性中,最高(且唯一)的数组索引属性是您推入的5
的属性,该属性位于索引0。
var person = [];
person.name = "Mr. White";
person.job= "Engineer";
person.push(5);
console.log(person[0]); // 5
console.log(person.hasOwnProperty(0)); // true
console.log(person.hasOwnProperty(1)); // false
// so the highest array index property that exists is 0
因此,数组的长度为1加该索引:0 + 1
或1
。
name
和job
属性不是数组索引,因此在标识length
时将完全忽略它们。