javascript中数组的长度如何确定?为什么此代码中数组对象的人的长度为1? [关闭]

问题描述 投票:-4回答:1
var person = [];
person.name = "Mr. White";
person.job= "Engineer";
person.push(5);

person.length的答案是什么,为什么?

javascript arrays
1个回答
2
投票

数组在其.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 + 11

namejob属性不是数组索引,因此在标识length时将完全忽略它们。

© www.soinside.com 2019 - 2024. All rights reserved.