What is Array.apply actually doing

后端 未结 3 601
盖世英雄少女心
盖世英雄少女心 2020-12-04 16:56

After reading this SO Question, I\'m still a little confused as to what Array.apply is actually doing. Consider the following snippet:

new Array(5).map(funct         


        
3条回答
  •  一个人的身影
    2020-12-04 17:07

    The Array constructor , when passed with a single numeric value (Let's say n) , creates a sparse Array of length n and has zero elements in it... so .map() wont work on it as explained by Dan Tao...

    let ar = Array(5); // Array(5) [ <5 empty slots> ]
    

    So , you can use .fill() method , that changes all elements in an array to given value, from a start index (default 0) to an end index (default array.length). It returns the modified array... So we can fill the empty (sparse) array with "undefined" value... It won't be sparse anymore...And finally, you can use .map() on returned array...

    let ar = Array(5).fill(undefined) ; // [undefined,undefined,undefined,undefined,undefined]
    let resultArray = ar.map(  el => Array(5).fill(undefined) );
    

    this resultArray will be a 5*5 array with every value of undefined...

    /* 
    [ [ undefined, undefined, undefined, undefined, undefined ],
      [ undefined, undefined, undefined, undefined, undefined ],
      [ undefined, undefined, undefined, undefined, undefined ],
      [ undefined, undefined, undefined, undefined, undefined ],
      [ undefined, undefined, undefined, undefined, undefined ] ]
    */
    

    :)

提交回复
热议问题