| 特性 | empty slot(空槽位) | undefined |
|---|---|---|
| 产生方式 | new Array(5) 这种写法创建稀疏数组 | 显式赋值:arr[0] = undefined |
| 是否有值 | 根本没有存储值(槽位不存在) | 有值,存的就是 undefined |
| 访问结果 | arr[i] // undefined(因为访问不到) | arr[i] // undefined |
| in 运算符 | i in arr // false | i in arr // true |
| hasOwnProperty | arr.hasOwnProperty(i) // false | arr.hasOwnProperty(i) // true |
| JSON.stringify | 会跳过空槽位 → "[null,null]" 或 "[,,,]" | 会保留 → "[null,undefined]" |
| map / forEach 遍历 | 会跳过该索引 | 会正常遍历该索引 |
| 表现差异示例 | [ , , 3] → length=3 但前两个是空槽位 | [undefined, undefined, 3] → length=3,前两个有值 |
const arr1 = new Array(3); // [ <3 empty items> ]const arr2 = [undefined, undefined, undefined];
console.log(0 in arr1); // false → 槽位不存在console.log(0 in arr2); // true → 有值 = undefined
console.log(arr1.hasOwnProperty(0)); // falseconsole.log(arr2.hasOwnProperty(0)); // true
arr1.forEach((x, i) => console.log(i, x)); // 不会打印任何东西arr2.forEach((x, i) => console.log(i, x)); // 打印 0 undefined, 1 undefined, 2 undefined👉 记忆口诀:
要不要我再帮你画个小图(比如数组槽位结构)来直观展示这俩的区别?