JavaScript function similar to Python range()

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

    pythonic mimics the Python range behaviour best it can using JS' generators (yield), supporting both the range(stop) and range(start, stop, step) use cases. In addition, pythonic's range function returns an Iterator object similar to Python that supports map and filter, so one could do fancy one-liners like:

    import {range} from 'pythonic';
    // ...
    const results = range(5).map(wouldBeInvokedFiveTimes);
    // `results` is now an array containing elements from
    // 5 calls to wouldBeInvokedFiveTimes
    

    Install using npm:

    npm install --save pythonic
    

    Disclosure I'm author and maintainer of Pythonic

提交回复
热议问题