I'm trying to set default values on an uninitialized array using the map function but it doesn't seem to work, any ideas on how to set default values?
Consider this code snippet I tried in Chrome console.
> var N = 10;
> var x = new Array(N);
> x
[undefined x 10]
> x.map(function(i) { return 0;});
[undefined x 10]
I was expecting the array to be initialized to 0's.
If you'd like to fill an array, you can use Array(5).fill()
and the methods will then work as expected--see the alternate related answer from aasha7. Older pre-fill approaches include:
Array.apply(null, new Array(5)).map(function() { return 0; });
// [ 0, 0, 0, 0, 0 ]
After some reading one of the posts linked in the comments, I found this can also be written as
Array.apply(null, {length: 5}).map(function() { return 0; });
However, trying to use .map
on undefined values will not work.
x = new Array(10);
x.map(function() { console.log("hello"); });
// so sad, no "hello"
// [ , , , , , , , , , ]
.map
will skip over undefined values :(
I'd just like to point out that you can now do:
Array(2).fill().map(_ => 4);
This will return [4, 4]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With