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?
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?
Share Improve this question asked Jan 29, 2021 at 13:53 Alex028502Alex028502 3,8442 gold badges29 silver badges58 bronze badges 7-
4
The
.map()
method (and others like it) skip uninitialized array positions. – Pointy Commented Jan 29, 2021 at 13:55 -
1
Try
Array(3).fill(null).map(x => 'a')
– Pointy Commented Jan 29, 2021 at 13:56 - thanks! that's funny how join is cool with it – Alex028502 Commented Jan 29, 2021 at 13:56
- 1 See: Why do I need to copy an array to use a method on it? – Nick Parsons Commented Jan 29, 2021 at 13:58
- 1 Thanks - I couldn't even think how to search for this! – Alex028502 Commented Jan 29, 2021 at 14:00
2 Answers
Reset to default 5you can use :
Array(3).fill(null).map(x => 'a')
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 pare 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')