Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - when I create an array of empty items, I can't use map with it

Tags:

javascript

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?

like image 977
Alex028502 Avatar asked Jun 21 '26 17:06

Alex028502


2 Answers

you can use :

Array(3).fill(null).map(x => 'a')
like image 82
ABlue Avatar answered Jun 23 '26 08:06

ABlue


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')
like image 41
Belhadjer Samir Avatar answered Jun 23 '26 07:06

Belhadjer Samir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!