Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.map not working as expected on uninitiated array

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?

Screenshot

like image 699
René Roth Avatar asked Dec 24 '22 06:12

René Roth


2 Answers

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.

like image 156
alex Avatar answered Dec 28 '22 23:12

alex


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>');
like image 36
Nina Scholz Avatar answered Dec 28 '22 23:12

Nina Scholz