JavaScript “new Array(n)” and “Array.prototype.map” weirdness

后端 未结 14 2083
粉色の甜心
粉色の甜心 2020-11-22 02:40

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:

14条回答
  •  萌比男神i
    2020-11-22 03:19

    Not a bug. That's how the Array constructor is defined to work.

    From MDC:

    When you specify a single numeric parameter with the Array constructor, you specify the initial length of the array. The following code creates an array of five elements:

    var billingMethod = new Array(5);
    

    The behavior of the Array constructor depends on whether the single parameter is a number.

    The .map() method only includes in the iteration elements of the array that have explicitly had values assigned. Even an explicit assignment of undefined will cause a value to be considered eligible for inclusion in the iteration. That seems odd, but it's essentially the difference between an explicit undefined property on an object and a missing property:

    var x = { }, y = { z: undefined };
    if (x.z === y.z) // true
    

    The object x does not have a property called "z", and the object y does. However, in both cases it appears that the "value" of the property is undefined. In an array, the situation is similar: the value of length does implicitly perform a value assignment to all the elements from zero through length - 1. The .map() function therefore won't do anything (won't call the callback) when called on an array newly constructed with the Array constructor and a numeric argument.

提交回复
热议问题