JavaScript Array Undefined Items

JavaScript Array Undefined Items

1月 27, 2021 · 1 分钟阅读时长 · 165 字 · -阅读 -评论

Recently encountered an issue where array iteration counts were incorrect due to uninitialized elements. This led to the discovery that array iteration counts don’t necessarily match the array length. Here’s a summary of this pitfall.

Example

 let array = [undefined, , 1, 2, 3];
      console.log(array[0]); // undefined
      console.log(array[1]); // undefined

      array.forEach((item, idx) => {
        console.log(item, idx);
      });

Output result:

Analysis

  1. Whether you assign undefined to an array item or leave it uninitialized, the value will be undefined

  2. During iteration, assigned items will be traversed, but unassigned items are skipped directly

    For example, when you need to control a fixed number of loops, you might write it like this. Note that fill() ensures array items are assigned as undefined. If you omit this, the iteration count will be 0

     new Array(10).fill().forEach((_, idx) => {
            console.log(idx + 1);
     });
    
Alan H
Authors
开发者,数码产品爱好者,喜欢折腾,喜欢分享,喜欢开源