How does `Array.from({length: 5}, (v, i) => i)` work?

后端 未结 4 1373
面向向阳花
面向向阳花 2020-12-24 12:48

I may be missing something obvious here but could someone breakdown step by step why Array.from({length: 5}, (v, i) => i) returns [0, 1, 2, 3, 4]

相关标签:
4条回答
  • 2020-12-24 13:08

    On developer.mozilla.org page about array.from, nobody tell us that mapFn can take 2 arguments, for example v and k: v is value of current element, k is index of element. So here's the deal.

    {length:5} create an object without any value, but with length equal to 5;

    (v, k) => k is an arrow function that assign index number of current element to that element value.

    0 讨论(0)
  • 2020-12-24 13:15

    When Javascript checks if a method can be called, it uses duck-typing. That means when you want to call a method foo from some object, which is supposed to be of type bar, then it doesn't check if this object is really bar but it checks if it has method foo.

    So in JS, it's possible to do the following:

    let fakeArray = {length:5};
    fakeArray.length //5
    let realArray = [1,2,3,4,5];
    realArray.length //5
    

    First one is like fake javascript array (which has property length). When Array.from gets a value of property length (5 in this case), then it creates a real array with length 5.

    This kind of fakeArray object is often called arrayLike.

    The second part is just an arrow function which populates an array with values of indices (second argument).

    This technique is very useful for mocking some object for test. For example:

    let ourFileReader = {}
    ourFileReader.result = "someResult"
    //ourFileReader will mock real FileReader
    
    0 讨论(0)
  • 2020-12-24 13:16

    var arr1 = Array.from({
        length: 5 // Create 5 indexes with undefined values
      },
      function(v, k) { // Run a map function on said indexes using v(alue)[undefined] and k(ey)[0 to 4]
        return k; // Return k(ey) as value for this index
      }
    );
    console.log(arr1);

    0 讨论(0)
  • 2020-12-24 13:22
    The 2nd argument in the arrow function is always the index with Array.from() method 
        x=Array.from({length:5},(v,i,k)=>k)
    console.log(x)
    //Expected output Array(5) [ undefined, undefined, undefined, undefined, undefined ]
        x=Array.from({length:5},(v,i,k)=>v)
    console.log(x)
    //Expected output Array(5) [ undefined, undefined, undefined, undefined, undefined ]
        x=Array.from({length:5},(v,i,k)=>i)
    console.log(x)
    //Expected output Array(5) [ 0, 1, 2, 3, 4 ]
    x=Array.from({length:5},()=>[])
    //Expected Output Array(5) [ [], [], [], [], [] ]
    x=Array.from({length:5},()=>{})
    //Expected Output Array(5) [ undefined, undefined, undefined, undefined, undefined ]
    
    0 讨论(0)
提交回复
热议问题