"Old style" array iterators (forEach
and friends) don't iterate over indexes that don't physically exist in an array ("holes"):
a = [0, 1, , 3, 4]
a.forEach(x => console.log(x))
(Compare this to a "new style" iterator):
a = [0, 1, , 3, 4]
for (let x of a)
console.log(x)
One way to detect holes is to run a counting old-style iterator over the array and compare the result to its length:
a = [0, 1, , 3, 4]
let count = a => a.reduce(c => c + 1, 0);
console.log(count(a) < a.length) // true -> has holes
If you're trying to detect any undefined value, both holes and "materialized" undefineds, use a "new style" spread to get a list of all values and apply some
or every
:
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))