Why do I need to copy an array to use a method on it?

前端 未结 4 1517
感动是毒
感动是毒 2020-11-28 13:30

I can use Array() to have an array with a fixed number of undefined entries. For example

Array(2); // [empty × 2] 

But if I go

4条回答
  •  佛祖请我去吃肉
    2020-11-28 14:02

    The reason is that the array element is unassigned. See here the first paragraph of the description. ... callback is invoked only for indexes of the array which have assigned values, including undefined.

    Consider:

    var array1 = Array(2);
    array1[0] = undefined;
    
    // pass a function to map
    const map1 = array1.map(x => x * 2);
    
    console.log(array1);
    console.log(map1);
    

    Outputs:

    Array [undefined, undefined]
    Array [NaN, undefined]
    

    When the array is printed each of its elements are interrogated. The first has been assigned undefined the other is defaulted to undefined.

    The mapping operation calls the mapping operation for the first element because it has been defined (through assignment). It does not call the mapping operation for the second argument, and simply passes out undefined.

提交回复
热议问题