4

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

René Roth
  • 1,979
  • 1
  • 18
  • 25

4 Answers4

4

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.

alex
  • 479,566
  • 201
  • 878
  • 984
3

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>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

from the fine manual:

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, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).

new Array(10)

creates missing elements, if that makes any sense.

Like this one:

var b=new Array();
b[30] = 1;
var c = b.map(function(){return 5;});

> [undefined × 30, 5]
Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72
1

There's an answer for this here: https://stackoverflow.com/a/5501711/6206601. Look at the top comment for further clarification.

Community
  • 1
  • 1
nbarbosa
  • 1,652
  • 1
  • 12
  • 10