JavaScript function similar to Python range()

前端 未结 24 1636
南旧
南旧 2020-11-30 21:17

Is there a function in JavaScript similar to Python\'s range()?

I think there should be a better way than to write the following lines every time:

24条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 21:29

    For a very simple range in ES6:

    let range = n => Array.from(Array(n).keys())
    

    From bigOmega's comment, this can be shortened using Spread syntax:

    let range = n => [...Array(n).keys()]
    

提交回复
热议问题