JavaScript function similar to Python range()

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

    Here is another es6 implementation of the range

    // range :: (from, to, step?) -> [Number]
    const range = (from, to, step = 1) => {
      //swap values if necesery
      [from, to] = from > to ? [to, from] : [from, to]
      //create range array
      return [...Array(Math.round((to - from) / step))]
        .map((_, index) => {
          const negative = from < 0 ? Math.abs(from) : 0
          return index < negative ? 
            from + index * step  :
            (index - negative + 1) * step
        })
    }  
    
    range(-20, 0, 5)
      .forEach(val => console.log(val))
    
    for(const val of range(5, 1)){
       console.log(`value ${val}`)
    }

    0 讨论(0)
  • No, there is none, but you can make one.

    JavaScript's implementation of Python's range()

    Trying to emulate how it works in Python, I would create function similar to this:

    function range(start, stop, step) {
        if (typeof stop == 'undefined') {
            // one param defined
            stop = start;
            start = 0;
        }
    
        if (typeof step == 'undefined') {
            step = 1;
        }
    
        if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
            return [];
        }
    
        var result = [];
        for (var i = start; step > 0 ? i < stop : i > stop; i += step) {
            result.push(i);
        }
    
        return result;
    };
    

    See this jsfiddle for a proof.

    Comparison between range() in JavaScript and Python

    It works in the following way:

    • range(4) returns [0, 1, 2, 3],
    • range(3,6) returns [3, 4, 5],
    • range(0,10,2) returns [0, 2, 4, 6, 8],
    • range(10,0,-1) returns [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
    • range(8,2,-2) returns [8, 6, 4],
    • range(8,2) returns [],
    • range(8,2,2) returns [],
    • range(1,5,-1) returns [],
    • range(1,5,-2) returns [],

    and its Python counterpart works exactly the same way (at least in the mentioned cases):

    >>> range(4)
    [0, 1, 2, 3]
    >>> range(3,6)
    [3, 4, 5]
    >>> range(0,10,2)
    [0, 2, 4, 6, 8]
    >>> range(10,0,-1)
    [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
    >>> range(8,2,-2)
    [8, 6, 4]
    >>> range(8,2)
    []
    >>> range(8,2,2)
    []
    >>> range(1,5,-1)
    []
    >>> range(1,5,-2)
    []
    

    So if you need a function to work similarly to Python's range(), you can use above mentioned solution.

    0 讨论(0)
  • 2020-11-30 21:27
    function range(start, stop) {
        if (typeof stop == 'undefined') {
            stop = start;
            start = 0;
        }
       
        result = [...Array(stop).keys()].slice(start, stop);
        return result;
    }
    
    0 讨论(0)
  • 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()]
    
    0 讨论(0)
  • 2020-11-30 21:30

    For getting an array of size x, here's an one-liner without using any library

    var range = n => Array(n + 1).join(1).split('').map((x, i) => i)
    

    works as

    > range(4)
    [0, 1, 2, 3]
    
    0 讨论(0)
  • 2020-11-30 21:33

    2018: this answer keeps getting upvotes, so here's an update. The code below is obsolete, but luckily ES6 standardized generators and the yield keyword, and they are universally supported across platforms. An example of the lazy range() using yield can be found here.


    In addition to what's already said, Javascript 1.7+ provides support for iterators and generators which can be used to create a lazy, memory-efficient version of range, simlar to xrange in Python2:

    function range(low, high) {  
        return {
            __iterator__: function() {
                return {  
                    next: function() {
                        if (low > high)
                            throw StopIteration;  
                        return low++;
                    }
                }
            }
        }
    }
    
    for (var i in range(3, 5))  
      console.log(i); // 3,4,5
    
    0 讨论(0)
提交回复
热议问题