JavaScript function similar to Python range()

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

    Here's a small extension for one of the answers in case you need to specify both starting and ending position of the range:

    let range = (start, end) => Array.from(Array(end + 1).keys()).slice(start);
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-11-30 21:35

    The following is a natural adaption of Python's range() function to JavaScript:

    // Generate range from start (inclusive) to stop (exclusive):
    function* range(start, stop, step = 1) {
       if (stop === undefined) [start, stop] = [0, start];
       if (step > 0) while (start < stop) yield start, start += step;
       else if (step < 0) while (start > stop) yield start, start += step;
       else throw new RangeError('range() step argument invalid');
    } 
    
    // Examples:
    console.log([...range(3)]);       // [0, 1, 2]
    console.log([...range(0, 3)]);    // [0, 1, 2]
    console.log([...range(0, 3, -1)]);// []
    console.log([...range(0, 0)]);    // []
    console.log([...range(-3)]);      // []
    console.log([...range(-3, 0)]);   // [-3, -2, -1]

    It supports any argument which can be compared to 0 and stop and can be incremented by step. It behaves identical to the Python version when used with numbers not exceeding Number.MAX_SAFE_INTEGER.

    Please note the following corner cases:

    [...range(0, 0, 0)];        // RangeError: range() step argument invalid
    [...range(Number.MAX_SAFE_INTEGER + 1, Number.MAX_SAFE_INTEGER + 2)];  // []
    [...range(Number.MAX_SAFE_INTEGER + 2, Number.MAX_SAFE_INTEGER + 3)];  // Infinite loop
    [...range(0.7, 0.8, 0.1)];  // [0.7, 0.7999999999999999]
    [...range('1', '11')];      // ['1']
    [...range('2', '22')];      // Infinite loop
    

    In contrast to @Tadeck's, @Volv's and @janka102's answer which return [], undefined or enter an infinite loop when step evaluates to 0 or NaN, this generator function throws an exception similar to Python's behavior.

    0 讨论(0)
  • 2020-11-30 21:36

    A port of the range function from Python 2 is provided by the underscore.js and lodash utility libraries (along with many other useful tools). Examples copied from the underscore docs:

    _.range(10);
    => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    _.range(1, 11);
    => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    _.range(0, 30, 5);
    => [0, 5, 10, 15, 20, 25]
    _.range(0, -10, -1);
    => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
    _.range(0);
    => []
    
    0 讨论(0)
  • 2020-11-30 21:36

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

    All of the solutions here are referring to Python 2's range (probably because of the code example you gave). However in Python 3, the range() method returns an iterator. JavaScript also has iterators and they're more space efficient than generating the whole array and storing it in memory.

    So the more accurate representation of Python 3's range(n) function is Array(n).keys().

    For example:

    for (let i of Array(n).keys()) {
      console.log(i) // 0, 1, 2, 3, ..., n
    }
    

    One more example (which has already been covered in the other answers). Converting the iterator to an array (ES6):

    let ary = [...Array(n).keys()];
    // ary = [0, 1, 2, 3, ..., n]
    
    0 讨论(0)
  • 2020-11-30 21:36

    This is my preferred way. It allows you to specify one or two inputs like in Python.

    function range(start, end) {
      return Array.from(Array(end||start).keys()).slice(!!end*start)
    }
    
    0 讨论(0)
提交回复
热议问题