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

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

    Numbers

    [...Array(5).keys()];
     => [0, 1, 2, 3, 4]
    

    Character iteration

    String.fromCharCode(...[...Array('D'.charCodeAt(0) - 'A'.charCodeAt(0) + 1).keys()].map(i => i + 'A'.charCodeAt(0)));
     => "ABCD"
    

    Iteration

    for (const x of Array(5).keys()) {
      console.log(x, String.fromCharCode('A'.charCodeAt(0) + x));
    }
     => 0,"A" 1,"B" 2,"C" 3,"D" 4,"E"
    

    As functions

    function range(size, startAt = 0) {
        return [...Array(size).keys()].map(i => i + startAt);
    }
    
    function characterRange(startChar, endChar) {
        return String.fromCharCode(...range(endChar.charCodeAt(0) -
                startChar.charCodeAt(0), startChar.charCodeAt(0)))
    }
    

    As typed functions

    function range(size:number, startAt:number = 0):ReadonlyArray<number> {
        return [...Array(size).keys()].map(i => i + startAt);
    }
    
    function characterRange(startChar:string, endChar:string):ReadonlyArray<string> {
        return String.fromCharCode(...range(endChar.charCodeAt(0) -
                startChar.charCodeAt(0), startChar.charCodeAt(0)))
    }
    

    lodash.js _.range() function

    _.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]
    String.fromCharCode(..._.range('A'.charCodeAt(0), 'D'.charCodeAt(0) + 1));
     => "ABCD"
    

    Old non es6 browsers without a library:

    Array.apply(null, Array(5)).map(function (_, i) {return i;});
     => [0, 1, 2, 3, 4]
    

    console.log([...Array(5).keys()]);

    (ES6 credit to nils petersohn and other commenters)

    0 讨论(0)
  • 2020-11-22 01:30

    Handy function to do the trick, run the code snippet below

    function range(start, end, step, offset) {
      
      var len = (Math.abs(end - start) + ((offset || 0) * 2)) / (step || 1) + 1;
      var direction = start < end ? 1 : -1;
      var startingPoint = start - (direction * (offset || 0));
      var stepSize = direction * (step || 1);
      
      return Array(len).fill(0).map(function(_, index) {
        return startingPoint + (stepSize * index);
      });
      
    }
    
    console.log('range(1, 5)=> ' + range(1, 5));
    console.log('range(5, 1)=> ' + range(5, 1));
    console.log('range(5, 5)=> ' + range(5, 5));
    console.log('range(-5, 5)=> ' + range(-5, 5));
    console.log('range(-10, 5, 5)=> ' + range(-10, 5, 5));
    console.log('range(1, 5, 1, 2)=> ' + range(1, 5, 1, 2));

    here is how to use it

    range (Start, End, Step=1, Offset=0);

    • inclusive - forward range(5,10) // [5, 6, 7, 8, 9, 10]
    • inclusive - backward range(10,5) // [10, 9, 8, 7, 6, 5]
    • step - backward range(10,2,2) // [10, 8, 6, 4, 2]
    • exclusive - forward range(5,10,0,-1) // [6, 7, 8, 9] not 5,10 themselves
    • offset - expand range(5,10,0,1) // [4, 5, 6, 7, 8, 9, 10, 11]
    • offset - shrink range(5,10,0,-2) // [7, 8]
    • step - expand range(10,0,2,2) // [12, 10, 8, 6, 4, 2, 0, -2]

    hope you find it useful.


    And here is how it works.

    Basically I'm first calculating the length of the resulting array and create a zero filled array to that length, then fill it with the needed values

    • (step || 1) => And others like this means use the value of step and if it was not provided use 1 instead
    • We start by calculating the length of the result array using (Math.abs(end - start) + ((offset || 0) * 2)) / (step || 1) + 1) to put it simpler (difference* offset in both direction/step)
    • After getting the length, then we create an empty array with initialized values using new Array(length).fill(0); check here
    • Now we have an array [0,0,0,..] to the length we want. We map over it and return a new array with the values we need by using Array.map(function() {})
    • var direction = start < end ? 1 : 0; Obviously if start is not smaller than the end we need to move backward. I mean going from 0 to 5 or vice versa
    • On every iteration, startingPoint + stepSize * index will gives us the value we need
    0 讨论(0)
  • 2020-11-22 01:31

    Using Harmony spread operator and arrow functions:

    var range = (start, end) => [...Array(end - start + 1)].map((_, i) => start + i);
    

    Example:

    range(10, 15);
    [ 10, 11, 12, 13, 14, 15 ]
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-22 01:33

    I would code something like this:

    function range(start, end) {
        return Array(end-start).join(0).split(0).map(function(val, id) {return id+start});
    }  
    
    range(-4,2);
    // [-4,-3,-2,-1,0,1]
    
    range(3,9);
    // [3,4,5,6,7,8]
    

    It behaves similarly to Python range:

    >>> range(-4,2)
    [-4, -3, -2, -1, 0, 1]
    
    0 讨论(0)
  • 2020-11-22 01:34

    Here's my 2 cents:

    function range(start, count) {
      return Array.apply(0, Array(count))
        .map((element, index) => index + start);
    }
    
    0 讨论(0)
提交回复
热议问题