数组可以包含“空槽”,这与用值undefined填充的槽不一样。空槽可以用以下方式创建:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const a = Array(5)
const b = [1,2,,,5]
let c = [1,2] c[4] = 5
const d = [1,2] d.length = 5
const e = [1, 2, 3, 4, 5]; delete e[2];
|
在某些操作中,空槽的行为就像它们被填入了undefined一样。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const arr = [1, 2, , , 5];
arr[2]
for (const i of arr) { console.log(i); }
const another = [...arr]
|
在其他方法中,特别是数组迭代中,空槽是被跳过的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| const arr = [1,2,,,5] const another = [...arr]
arr.map((i) => i + 1) another.map((i) => i + 1)
arr.forEach((i) => console.log(i)) another.forEach((i) => console.log(i))
arr.filter(() => true)
another.filter(() => true)
arr.some((k) => !k);
another.some((k) => !k);
Object.keys(arr)
Object.keys(another)
Object.values(arr)
Object.values(another)
for (const key in arr) { console.log(key); }
for (const key in another) { console.log(key); }
const target = {...arr}
const target1 = {...another}
|
稀疏数组中的空槽在数组方法之间的行为不一致。通常,旧方法会跳过空槽,而新方法将它们视为 undefined。