5

I tried this


> Array(3)
[ <3 empty items> ]
> // and this joins up all the nothings
> Array(3).join('-')
'--'
> // but...
> Array(3).map((x) => 'a')
[ <3 empty items> ]
> // map doesn't work with the array of empty items!

and I thought I would get the same result as this

> [undefined, undefined, undefined].map((x) => 'a')
[ 'a', 'a', 'a' ]

What's up with that?

Alex028502
  • 3,486
  • 2
  • 23
  • 50

2 Answers2

4

you can use :

Array(3).fill(null).map(x => 'a')
ABlue
  • 664
  • 6
  • 20
3

in the first case you creates an array with undefined pointers.

Array(3)

And the second creates an array with pointers to 3 undefined objects, in this case the pointers them self are NOT undefined, only the objects they point to.

[undefined, undefined, undefined]

when we compare the two case it's look like this

//first case look like this 
[undefined, undefined, undefined]
//the second look like this 
 Array(3) [,,,];

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. In the first case array values have not explicitly assigned values, whereas in the seconds example were assigned, even if it was the value undefined link

for you example you have to do this

Array(3).fill(undefined).map(x => 'a')
Belhadjer Samir
  • 1,461
  • 7
  • 15