javascriptarraysmap-function

Why does the `map` method apparently not work on arrays created via `new Array(count)`?


I've observed this in Firefox-3.5.7/Firebug-1.5.3 and Firefox-3.6.16/Firebug-1.6.2

When I fire up Firebug:

var x = new Array(3)
console.log(x) 
// [undefined, undefined, undefined]

var y = [undefined, undefined, undefined]
console.log(y) 
// [undefined, undefined, undefined]

console.log(x.constructor == y.constructor) // true

console.log( 
  x.map(function() { return 0; })
)
// [undefined, undefined, undefined]

console.log(
  y.map(function() { return 0; })
)
// [0, 0, 0]

What's going on here? Is this a bug, or am I misunderstanding how to use new Array(3)?


Solution

  • It appears that the first example

    x = new Array(3);
    

    Creates an array with a length of 3 but without any elements, so the indices [0], [1] and [2] is not created.

    And the second creates an array with the 3 undefined objects, in this case the indices/properties them self are created but the objects they refer to are undefined.

    y = [undefined, undefined, undefined]
    // The following is not equivalent to the above, it's the same as new Array(3)
    y = [,,,];
    

    As map runs on the list of indices/properties, not on the set length, so if no indices/properties is created, it will not run.