The problem description is not comprehensive
My problem is that when my array is defined as follows:
let a = [undefined, undefined] a[9] = 1 console.log(a) //[undefined, undefined, undefined × 7, 1]
Is there any difference between the automatically generated undefined here and the one I defined?
Why can’t I traverse them when I use the built-in traversal?
a.forEach(it => console.log(it)) // 也只会有三个结果
Because what you define is a sparse array (sparse array, the array length is larger than the number of array elements). You can use
in
to detect whether its array elements exist:And
forEach
will only traverse the elements where the original index exists.This is a trap of arrays, this undefined is not that undefined. The automatically generated ones are called "empty slots", and chrome just shows them as undefined. You can also see that the real undefined is output one by one, and the empty slots output the words "undefined × 7".
forEach, map and the like will skip empty slots. Please refer to the solution
Because forEach is written like this, the built-in forEach will continue when it encounters undefined
You can write a non-skipping version yourself
You can think about this problem from another angle:
var a = [1,2,3,4]
delete a[0]
console.log(a)//[undefined × 1, 2, 3, 4]
a.length//4
a.forEach(it=>console.log(it))// 2 3 4
Back to the question, when forEach is encapsulated, this "undefined" will be skipped, you can rewrite it Try this method, no matter what the value is, it should be able to be printed normally