数组只是JS中的一种特殊对象。有一个特殊的语法,这很好,因为它使我们可以有效地使用它们。想象这样写一个数组文字将是多么乏味:
const array = {0: 'foo', 1: 'bar', 2: 'baz'}
但是它们仍然是对象。因此,如果您这样做:
const myArray = [42, 'foo', 'bar', 'baz'];
myArray[-1] = 'I am not here';
myArray['whatever'] = 'Hello World';
这些非整数属性将附加到对象(数组是哪个),但是某些本机方法无法访问这些属性,例如 Array.length
。
您可以假定本机的“长度”方法是一种吸气剂,它计算所有属性(索引是属性,而值是实际值)可转换为正整数或零的)进行。像这样的伪实现:
根据规范,本机length
方法(作为getter(exampleArray.length
))将检查所有小于2 32的“负整数”的”键,获取最大的键并返回其数值+ 1。
作为设置器(exampleArray.length = 42
),如果给定长度大于非负整数键的实际数量,它将为“丢失”索引创建一些空位,或者删除所有不大于整数的非负整数键(及其值)。给定的长度。
伪实现:
const myArray = {
'-1': 'I am not here',
0: 42,
1: 'foo',
2: 'bar',
3: 'baz',
whatever: 'Hello World',
get myLength() {
let highestIndex = -1;
for (let key in this) {
let toInt = parseInt(key, 10);
if (!Number.isNaN(toInt) && toInt > -1) {
if (toInt > highestIndex) highestIndex = toInt;
}
}
return highestIndex + 1;
},
set myLength(newLength) {
}
}
console.log(myArray.myLength);
myArray[9] = 'foobar';
console.log(myArray.myLength);