skip to Main Content

I tried to create an array of HtmlImageElement using a map on an other array.

const foo = Array(5).map(() => new Image())

And I got an array full of empty object

node example of the previous code line, returning "[<5 empty items>]"

Why is that ?

Thanks !

Edit :

It looks like it is the case with any object constructed in a map

node example of the same line of code but with a custom object, also returning an array of empty object

2

Answers


  1. From the doc : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array

    arrayLength If the only argument passed to the Array constructor is an integer between 0 and 232 – 1 (inclusive), this returns a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values — see sparse arrays).

    More explanation on sparse arrays here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays

    Login or Signup to reply.
  2. Array(5) creates a new empty array of a length 5 with all the items as undefined. Calling map() on this empty array has no effect on the callback function (will not be executed).

    To solve the issue, you can try Array.from() like following way:

    const foo = Array.from({length:5}, () => new Image());
    console.log(foo);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search