Mapping Array in Javascript with sequential numbers

后端 未结 4 1862
逝去的感伤
逝去的感伤 2021-02-04 17:40

The following code:

let myArray = Array.apply(null, {length: 10}).map(Number.call, Number);

Creates the following Array:

[0, 1,         


        
4条回答
  •  一整个雨季
    2021-02-04 18:30

    Array.apply(null, {length: 10})
    

    creates an array of length 10 with all elements being undefined.

    .map(Number.call, Number)
    

    will invoke Number.call for each element with the arguments (element, index, array) and setting this to Number. The first argument to call will be taken as this (not relevant here), and all the other arguments are passed as they are, with the first one being the index. And Number will now convert its first argument, index, to a number (here: will return the index, as it is a number), and that's what map will write to its return array.

提交回复
热议问题