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

后端 未结 14 2071
粉色の甜心
粉色の甜心 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:19

    In ECMAScript 6th edition specification.

    new Array(3) only define property length and do not define index properties like {length: 3}. see https://www.ecma-international.org/ecma-262/6.0/index.html#sec-array-len Step 9.

    [undefined, undefined, undefined] will define index properties and length property like {0: undefined, 1: undefined, 2: undefined, length: 3}. see https://www.ecma-international.org/ecma-262/6.0/index.html#sec-runtime-semantics-arrayaccumulation ElementList Step 5.

    methods map, every, some, forEach, slice, reduce, reduceRight, filter of Array will check the index property by HasProperty internal method, so new Array(3).map(v => 1) will not invoke the callback.

    for more detail, see https://www.ecma-international.org/ecma-262/6.0/index.html#sec-array.prototype.map

    How to fix?

    let a = new Array(3);
    a.join('.').split('.').map(v => 1);
    
    let a = new Array(3);
    a.fill(1);
    
    let a = new Array(3);
    a.fill(undefined).map(v => 1);
    
    let a = new Array(3);
    [...a].map(v => 1);
    

提交回复
热议问题