2

Trying to find a way to inline the creation of an array of data given its size, i tried

var n = 4;
var data = (new Array(n)).map(function(x) { return 1 });

which gave me

[undefined, undefined, undefined, undefined]

Regarding that

new Array(n)

gives

[undefined, undefined, undefined, undefined]

and that

[undefined, undefined, undefined, undefined].map(function(x) { return 1 });

returns

[1, 1, 1, 1]

I would expect to be able to chain the Array constructor and the map function.

Any insights on that behavior ?

zrz
  • 340
  • 2
  • 10

1 Answers1

6

new Array(n) creates an array of size n, but with no elements in it. This is called a sparse array. Though there are no elements in the array, the browser represents them as undefined. And Array.prototype.map will ignore the array elements which are not defined yet.

Quoting from the ECMA 5.1 Specification for Array.prototype.map,

callbackfn is called only for elements of the array which actually exist; it is not called for missing elements of the array.

To be able to chain the map function, you might want to do like this

console.log(Array.apply(null, {length: n}).map(function(x) { return 1 }));
# [ 1, 1, 1, 1 ]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • Thanks! I also noticed that the browser representation is actually different (Chrome) : new Array(2) returns [undefined x2] not [undefined, undefined] – zrz May 24 '14 at 15:22