0

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

damjuve
  • 314
  • 4
  • 10
  • 2
    Your list is of length 5 but contains "nothing", so you should fill it with something before you map. `Array(5).fill(undefined).map(() => new Image())` – kemicofa ghost Jul 13 '23 at 09:21
  • 1
    After creating your array via `Array()` constructor, you have to call `.fill()` to set some value for every element in the array, then it can be `.map()`ed. Example: `Array(5).fill().map(() => ({any: 'object'}))` – webgodo Jul 13 '23 at 09:24

2 Answers2

0

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

Christophe Quintard
  • 1,858
  • 1
  • 22
  • 30
0

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);
Mamun
  • 66,969
  • 9
  • 47
  • 59