How to create an array containing 1…N

后端 未结 30 1912
旧时难觅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:52

    You can use Array fill and map from Es6; just like some few people suggested in the answers they gave for this question. Below are some few examples:

    Example-One: Array(10).fill(0).map((e,i)=>i+1)
    
    Result-One: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    Example-Two: Array(100/10).fill(0).map((e,i)=>(i*10)+10)
    
    Result-Two:[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    
    

    I prefer this because I find it straight forward and easier.

提交回复
热议问题