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 ?

0

1 Answer 1

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 ]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I also noticed that the browser representation is actually different (Chrome) : new Array(2) returns [undefined x2] not [undefined, undefined]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.