I'd like to understand the why behind this:
var a = new Array(3);
var b = a.map(function () {
return 'b';
});
results in
a: [ , , ]
b: [ , , ]
When I would expect b to result in ['b', 'b', 'b']
.
In further investigation, I discovered that if i were to do a.push('a')
, I'd have [, , , 'a']
.
And after the map function, b
would become [, , , 'b']
.
What's going on here? Why do these allocated cells behave differently from the initialization? I was originally expecting this to act as it would if it was an array literal, [undefined, undefined, undefined].map(fn)
Array.map() does not invoke the callback for indexes whose values aren't defined.
From MDN docs:
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 that are undefined, those which have been deleted or which have never been assigned values.
©2020 All rights reserved.