search

Home  >  Q&A  >  body text

javascript - Why is the undefined array in js not traversed?

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))    // 也只会有三个结果
PHP中文网PHP中文网2706 days ago960

reply all(4)I'll reply

  • 某草草

    某草草2017-07-05 10:52:19

    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:

    '0' in a  // true,索引存在.
    '1' in a  // true
    '2' in a  // false,索引不存在
    '9' in a  // true

    And forEach will only traverse the elements where the original index exists.

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-07-05 10:52:19

    Is there any difference between the automatically generated undefined here and the one I defined?

    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

    console.log(Array.from(a))

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-07-05 10:52:19

    Because forEach is written like this, the built-in forEach will continue when it encounters undefined
    You can write a non-skipping version yourself

    reply
    0
  • 漂亮男人

    漂亮男人2017-07-05 10:52:19

    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

    reply
    0
  • Cancelreply