You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中空值(Empty)与Undefined的差异及识别方法

区分数组空位与明确赋值的undefined

在JavaScript中,Array(10)创建的数组包含空位(empty slots),而Array(10).fill(undefined)创建的数组是明确赋值了undefined的元素,两者访问时都返回undefined,但可以通过以下几种可靠方式区分:

1. 使用Object.hasOwn()检查自有属性

数组的空位并非数组对象的自有属性,而明确赋值的undefined会成为数组的自有属性,因此可以用Object.hasOwn()(推荐)或hasOwnProperty()判断:

const emptyArr = Array(10);
const filledArr = Array(10).fill(undefined);

// 检查索引0的元素状态
console.log(Object.hasOwn(emptyArr, 0));  // false → 空位
console.log(Object.hasOwn(filledArr, 0)); // true → 明确的undefined

2. 利用Array.prototype.includes()的行为差异

includes()方法不会将空位视为undefined,因此可以通过该方法区分:

console.log(emptyArr.includes(undefined));  // false → 空位不匹配undefined
console.log(filledArr.includes(undefined)); // true → 明确的undefined能被匹配

3. 遍历方法的行为差异

多数数组遍历方法会跳过空位,但会处理明确赋值的undefined:

  • forEach():直接跳过空位,不会执行回调
  • for...in:仅遍历存在的数组索引(即明确赋值的元素)

示例:

let emptyCount = 0;
emptyArr.forEach(() => emptyCount++);
console.log(emptyCount); // 0 → 空位被跳过

let filledCount = 0;
filledArr.forEach(() => filledCount++);
console.log(filledCount); // 10 → 每个元素都触发回调

4. 利用Number()转换的特性(需谨慎)

如你提到的,空位通过Number()转换会得到0,而undefined转换会得到NaN,但这种方式仅适用于确定元素不是0的场景,否则会混淆:

console.log(Number(emptyArr[0]));  // 0 → 空位转换结果
console.log(Number(filledArr[0])); // NaN → undefined转换结果

内容的提问来源于stack exchange,提问作者idk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 10:11:04