Using .map()
on an array full of undefined values (eg new Array(10)
) will always return an array of the same length with undefined values, no matter what you return.
new Array(10).map(function(){return 5;});
will return a new array filled with 10x undefined. Why does this happen?
Because when you define an array like that, the spaces for values are empty slots and are not iterated over by map()
or any of its friends.
There is Array.prototype.fill()
(in ES6) which can be used to set values on that array.
You could use
var array = Array.apply(null, { length: 10 }).map(function(){ return 5; });
var array = Array.apply(null, { length: 10 }).map(function() { return 5; });
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
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