如何获取JavaScript数组中空元素(空槽、null、undefined)的索引
问题根源
你遇到的问题本质是对JavaScript数组空值类型的判断逻辑不匹配:
- 用
['a',,'b']语法创建的数组,中间的空位是空槽(empty slot),访问空槽位置的元素时会返回undefined,和显式赋值为undefined的元素取值表现一致 - 你原来的判断逻辑
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
相关产品推荐
相关产品推荐

