外观
稀疏数组
稀疏数组是包含未定义索引的数组,未定义的索引会成为空插槽(empty slots),连 undefined 都不是,在浏览器控制台打印的表现形式一般会是 empty。

访问空插槽时会返回 undefined。
创建方式
构造函数只传一个参数
Array 构造函数传一个参数时会该参数为指定数组长度。
此例创建长度为 3 的稀疏数组,此时数组不存储任何值,索引属性 0、1 等都没定义。
js
const arr = new Array(3)数组字面量
使用连续的逗号,数组字面量语法允许尾随逗号,所以 [,,,] 的长度是 3 而不是 4。
js
const arr = [,,,]修改数组元素时索引大于 length
js
const arr = []
arr[3] = 100length 值设置成大于当前值
js
const arr = []
arr.length = 3使用 delete 删除元素
js
const arr = [1, 2, 3]
delete arr[1]检测空插槽
使用 in 运算符可检测空插槽。
js
const arr = [1,,undefined,4]
console.log(1 in arr) // false,索引 1 不存在
console.log(2 in arr) // true,即便值为 undefined实际意义
认识稀疏数组是为了代码行为符合预期,如使用 delete 删除了一个数组元素后 length 的值不会变,以为循环次数会跟 length 一致,但数组的 forEach() 等方法会跳过空插槽,实际循环的次数会变少,出于意料的行为可能会导致 BUG。
js
const arr = [1, 2, 3]
delete arr[1]
arr.forEach(item => console.log(item))
// 1
// 3注意事项
- 空插槽意味着该属性不存在,所以 for...in 循环会跳过空插槽,而普通 for 循环是根据
length来遍历的,所以不会跳过空插槽,for-of 循环也不会。 forEach()、map()、filter()、every()、some()、reduce()数组方法会跳过空插槽。find()、findIndex()、keys()、values()、entries()方法不会跳过空插槽。JSON.stringify()序列化时空插槽会转为null。
可通过方法语义来记忆,像 forEach() 等方法,目的是“对数组中的每个元素执行操作”,空插槽不是元素,所以会跳过。而 find() 等方法,目的是“遍历数组的所有索引位置”,空插槽是数组一部分,所以应被考虑。