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

后端 未结 14 1899
粉色の甜心
粉色の甜心 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条回答
  •  借酒劲吻你
    2020-11-22 03:34

    The arrays are different. The difference is that new Array(3) creates an array with a length of three but no properties, while [undefined, undefined, undefined] creates an array with a length of three and three properties called "0", "1" and "2", each with a value of undefined. You can see the difference using the in operator:

    "0" in new Array(3); // false
    "0" in [undefined, undefined, undefined]; // true
    

    This stems from the slightly confusing fact that if you try to get the value of a non-existent property of any native object in JavaScript, it returns undefined (rather than throwing an error, as happens when you try to refer to a non-existent variable), which is the same as what you get if the property has previously been explictly set to undefined.

提交回复
热议问题