数组中的空元素未被评估为未定义



我的目标是检查整数数组中是否存在空值>0:

给定const array = [1, 4, , 7, 14],我期望测试返回false。您可以通过!array.includes(undefined)获得该结果

但是如果我使用函数array.every(el => el !== undefined),它的计算结果是真的?那么,js数组中的空元素是未定义的还是完全不同的数据类型?

"旧式"数组迭代器(forEach和友元(不会迭代数组中物理上不存在的索引("孔"(:

a = [0, 1, , 3, 4]
a.forEach(x => console.log(x))

(将其与"新样式"迭代器进行比较(:

a = [0, 1, , 3, 4]
for (let x of a)
console.log(x)

检测漏洞的一种方法是在数组上运行计数旧式迭代器,并将结果与其长度进行比较:

a = [0, 1, , 3, 4]
let count = a => a.reduce(c => c + 1, 0);
console.log(count(a) < a.length) // true -> has holes

如果你试图检测任何未定义的值;物化";undefineds,使用";新风格";展开以获得所有值的列表,并应用someevery:

a = [0, 1, , 2, 4]
console.log([...a].some(x => x === undefined))

a = [0, 1, undefined, 2, 4]
console.log([...a].some(x => x === undefined))

使用Object.getOwnPropertyNames()Array.prototype.slice()

const array1 = [1, 4, , 7, 14],
array2 = [1, 2, 3, 4],
res = (array) =>
Object.getOwnPropertyNames(array).slice(0, -1).length === array.length
? "No Empty"
: "Yes Empty";
console.log(res(array1));
console.log(res(array2));

相关内容

最新更新