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

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

    ... more range, using a generator function.

    function range(s, e, str){
      // create generator that handles numbers & strings.
      function *gen(s, e, str){
        while(s <= e){
          yield (!str) ? s : str[s]
          s++
        }
      }
      if (typeof s === 'string' && !str)
        str = 'abcdefghijklmnopqrstuvwxyz'
      const from = (!str) ? s : str.indexOf(s)
      const to = (!str) ? e : str.indexOf(e)
      // use the generator and return.
      return [...gen(from, to, str)]
    }
    
    // usage ...
    console.log(range('l', 'w'))
    //=> [ 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w' ]
    
    console.log(range(7, 12))
    //=> [ 7, 8, 9, 10, 11, 12 ]
    
    // first 'o' to first 't' of passed in string.
    console.log(range('o', 't', "ssshhhooooouuut!!!!"))
    // => [ 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 't' ]
    
    // only lowercase args allowed here, but ...
    console.log(range('m', 'v').map(v=>v.toUpperCase()))
    //=> [ 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V' ]
    
    // => and decreasing range ...
    console.log(range('m', 'v').map(v=>v.toUpperCase()).reverse())
    
    // => ... and with a step
    console.log(range('m', 'v')
              .map(v=>v.toUpperCase())
              .reverse()
              .reduce((acc, c, i) => (i % 2) ? acc.concat(c) : acc, []))
    
    // ... etc, etc.
    

    Hope this is useful.

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

    For numbers you can use ES6 Array.from(), which works in everything these days except IE:

    Shorter version:

    Array.from({length: 20}, (x, i) => i);
    

    Longer version:

    Array.from(new Array(20), (x, i) => i);​​​​​​
    

    which creates an array from 0 to 19 inclusive. This can be further shortened to one of these forms:

    Array.from(Array(20).keys());
    // or
    [...Array(20).keys()];
    

    Lower and upper bounds can be specified too, for example:

    Array.from(new Array(20), (x, i) => i + *lowerBound*);
    

    An article describing this in more detail: http://www.2ality.com/2014/05/es6-array-methods.html

    0 讨论(0)
  • 2020-11-22 01:56
    Array.range = function(a, b, step){
        var A = [];
        if(typeof a == 'number'){
            A[0] = a;
            step = step || 1;
            while(a+step <= b){
                A[A.length]= a+= step;
            }
        }
        else {
            var s = 'abcdefghijklmnopqrstuvwxyz';
            if(a === a.toUpperCase()){
                b = b.toUpperCase();
                s = s.toUpperCase();
            }
            s = s.substring(s.indexOf(a), s.indexOf(b)+ 1);
            A = s.split('');        
        }
        return A;
    }
        
        
    Array.range(0,10);
    // [0,1,2,3,4,5,6,7,8,9,10]
        
    Array.range(-100,100,20);
    // [-100,-80,-60,-40,-20,0,20,40,60,80,100]
        
    Array.range('A','F');
    // ['A','B','C','D','E','F')
        
    Array.range('m','r');
    // ['m','n','o','p','q','r']
    
    0 讨论(0)
  • 2020-11-22 01:56

    The standard Javascript doesn't have a built-in function to generate ranges. Several javascript frameworks add support for such features, or as others have pointed out you can always roll your own.

    If you'd like to double-check, the definitive resource is the ECMA-262 Standard.

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

    My codegolfing coworker came up with this (ES6), inclusive:

    (s,f)=>[...Array(f-s+1)].map((e,i)=>i+s)
    

    non inclusive:

    (s,f)=>[...Array(f-s)].map((e,i)=>i+s)
    
    0 讨论(0)
  • 2020-11-22 01:57

    Complete ES6 implementation using range([start, ]stop[, step]) signature:

    function range(start, stop, step=1){
      if(!stop){stop=start;start=0;}
      return Array.from(new Array(int((stop-start)/step)), (x,i) => start+ i*step)
    }
    

    If you want automatic negative stepping, add

    if(stop<start)step=-Math.abs(step)
    

    Or more minimalistically:

    range=(b, e, step=1)=>{
      if(!e){e=b;b=0}
      return Array.from(new Array(int((e-b)/step)), (_,i) => b<e? b+i*step : b-i*step)
    }
    

    If you have huge ranges look at Paolo Moretti's generator approach

    0 讨论(0)
提交回复
热议问题