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

如何获取JavaScript数组中空元素(空槽、null、undefined)的索引

问题根源

你遇到的问题本质是对JavaScript数组空值类型的判断逻辑不匹配:

  1. 用['a',,'b']语法创建的数组,中间的空位是空槽(empty slot),访问空槽位置的元素时会返回undefined,和显式赋值为undefined的元素取值表现一致
  2. 你原来的判断逻辑array[i] === undefined只能匹配空槽和显式undefined,无法匹配null、空字符串等你提到的其他空元素类型

解决方案

根据你需要匹配的空值范围选择对应方案:

方案1:匹配空槽、null、undefined三类空值

用== null的宽松判断,自动命中null和undefined(空槽取值为undefined也会命中):

const array = ['red', , 'orange', , 'blue', 'white', 'black', null, undefined];
const emptyIndexes = [];

for (let i = 0; i < array.length; i++) {
  if (array[i] == null) {
    console.log('No color: ' + i);
    emptyIndexes.push(i);
  }
}

// 输出结果:1、3、7、8

方案2:额外包含空字符串''的匹配

调整判断条件即可:

if (array[i] == null || array[i] === '')

方案3:仅匹配纯空槽(排除显式赋值的undefined)

如果需要区分空槽和显式赋值为undefined的有效元素,用Object.hasOwn()判断索引是否真实存在于数组上:

const array = ['red', , 'orange', undefined, 'blue', 'white', 'black'];
const emptySlotIndexes = [];

for (let i = 0; i < array.length; i++) {
  if (!Object.hasOwn(array, i)) {
    console.log('Empty slot: ' + i);
    emptySlotIndexes.push(i);
  }
}

// 输出结果:1,不会匹配显式赋值undefined的索引3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 00:30:04