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

后端 未结 4 1377
面向向阳花
面向向阳花 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.

提交回复
热议问题