JavaScript function similar to Python range()

前端 未结 24 1598
南旧
南旧 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:33

    Further refined with ES6 default parameters.

    let range = function*(start = 0, stop, step = 1) {
      let cur = (stop === undefined) ? 0 : start;
      let max = (stop === undefined) ? start : stop;
      for (let i = cur; step < 0 ? i > max : i < max; i += step)
        yield i
    }
    

提交回复
热议问题