srfrnk
srfrnk

Reputation: 2519

JavaScript Array weird initialization

I've stumbled upon something strange.... Maybe someone can try explaining the difference between these two:

var a1=Array(2);
var a2=Array.apply(null,a1);
console.log(a1);
console.log(a2);
console.log(a1[0]===a2[0]);

notice the items are equal but the console log of the arrays looks different (on Chrome and NodeJS).

also other aspects of them seem to work differently:

a1.map(function(i){console.log("!");})
a2.map(function(i){console.log("!");})

notice that map itereares only for a2 not for a1.

this happens on NodeJS, Chrome and FF.

Upvotes: 2

Views: 115

Answers (1)

Hrishi
Hrishi

Reputation: 7138

In JavaScript, this creates a sparse array:

var a = new Array(3) // a = [ , , ,]

if you try to iterate over a using map or forEach, JavaScript skips the holes. The invocation

var b = Array.apply(null, Array(3)) // b = [undefined, undefined, undefined]

(this is equivalent to invoking the array constructor with Array(undefined, undefined, undefined))

creates a dense array b. b is almost the same as a but now, you can iterate over the elements, in other words, since the array is now dense, map and foreach don't skip over elements.

Upvotes: 4

Related Questions