How to create an array containing 1…N

后端 未结 30 1542
旧时难觅i
旧时难觅i 2020-11-22 01:04

I\'m looking for any alternatives to the below for creating a JavaScript array containing 1 through to N where N is only known at runt

30条回答
  •  青春惊慌失措
    2020-11-22 01:59

    Just another ES6 version.

    By making use of Array.from second optional argument:

    Array.from(arrayLike[, mapFn[, thisArg]])

    We can build the numbered array from the empty Array(10) positions:

    Array.from(Array(10), (_, i) => i)
    

    var arr = Array.from(Array(10), (_, i) => i);
    document.write(arr);

提交回复
热议问题