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

后端 未结 30 2757
广开言路
广开言路 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:33

    --- UPDATE (Thanks to @lokhmakov for simplification) ---

    Another version using ES6 generators ( see great Paolo Moretti answer with ES6 generators ):

    const RANGE = (x,y) => Array.from((function*(){
      while (x <= y) yield x++;
    })());
    
    console.log(RANGE(3,7));  // [ 3, 4, 5, 6, 7 ]
    

    Or, if we only need iterable, then:

    const RANGE_ITER = (x,y) => (function*(){
      while (x <= y) yield x++;
    })();
    
    for (let n of RANGE_ITER(3,7)){
      console.log(n);
    }
    
    // 3
    // 4
    // 5
    // 6
    // 7
    

    --- ORGINAL code was: ---

    const RANGE = (a,b) => Array.from((function*(x,y){
      while (x <= y) yield x++;
    })(a,b));
    

    and

    const RANGE_ITER = (a,b) => (function*(x,y){
      while (x <= y) yield x++;
    })(a,b);
    

提交回复
热议问题