Does JavaScript have a method like “range()” to generate a range within the supplied bounds?

后端 未结 30 3219
广开言路
广开言路 2020-11-22 00:51

In PHP, you can do...

range(1, 3); // Array(1, 2, 3)
range(\"A\", \"C\"); // Array(\"A\", \"B\", \"C\")

That is, there is a function that l

30条回答
  •  春和景丽
    2020-11-22 01:34

    You can use lodash or Undescore.js range:

    var range = require('lodash/range')
    range(10)
    // -> [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
    

    Alternatively, if you only need a consecutive range of integers you can do something like:

    Array.apply(undefined, { length: 10 }).map(Number.call, Number)
    // -> [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
    

    In ES6 range can be implemented with generators:

    function* range(start=0, end=null, step=1) {
      if (end == null) {
        end = start;
        start = 0;
      }
    
      for (let i=start; i < end; i+=step) {
        yield i;
      }
    }
    

    This implementation saves memory when iterating large sequences, because it doesn't have to materialize all values into an array:

    for (let i of range(1, oneZillion)) {
      console.log(i);
    }
    

提交回复
热议问题