特性empty slot(空槽位)undefined
产生方式new Array(5) 这种写法创建稀疏数组显式赋值:arr[0] = undefined
是否有值根本没有存储值(槽位不存在)有值,存的就是 undefined
访问结果arr[i] // undefined(因为访问不到)arr[i] // undefined
in 运算符i in arr // falsei in arr // true
hasOwnPropertyarr.hasOwnProperty(i) // falsearr.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)); // false
console.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

👉 记忆口诀:

  • empty slot:没存值 → “缺席”
  • undefined:有存值 → “到场但空着”

要不要我再帮你画个小图(比如数组槽位结构)来直观展示这俩的区别?