代码之家  ›  专栏  ›  技术社区  ›  alex

javascript是否有类似“range()”的方法在提供的界限内生成范围?

  •  609
  • alex  · 技术社区  · 14 年前

    在PHP中,您可以……

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

    也就是说,有一个函数可以让您通过传递上界和下界来获得数字或字符的范围。

    有没有内置到本机的javascript中?如果没有,我将如何实现它?

    50 回复  |  直到 6 年前
        1
  •  949
  •   Ben    6 年前

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

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

    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"
    

    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)))
    }
    

    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)))
    }
    

    _.range()

    _.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"
    

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

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

        2
  •  262
  •   dman    7 年前

    Array.from() which works in everything these days

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

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

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

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

    http://www.2ality.com/2014/05/es6-array-methods.html

        3
  •  91
  •   Kutyel    6 年前

    Array(10).fill(1).map((x, y) => x + y)
    

    step

    const range = (start, stop, step = 1) =>
      Array(Math.ceil((stop - start) / step)).fill(start).map((x, y) => x + y * step)
    
        4
  •  90
  •   Kutyel    6 年前

    function range(start, count) {
      return Array.apply(0, Array(count))
        .map((element, index) => index + start);
    }
    
        5
  •  65
  •   mplungjan Gvidas    8 年前

    var range = function(start, end, step) {
        var range = [];
        var typeofStart = typeof start;
        var typeofEnd = typeof end;
    
        if (step === 0) {
            throw TypeError("Step cannot be zero.");
        }
    
        if (typeofStart == "undefined" || typeofEnd == "undefined") {
            throw TypeError("Must pass start and end arguments.");
        } else if (typeofStart != typeofEnd) {
            throw TypeError("Start and end arguments must be of same type.");
        }
    
        typeof step == "undefined" && (step = 1);
    
        if (end < start) {
            step = -step;
        }
    
        if (typeofStart == "number") {
    
            while (step > 0 ? end >= start : end <= start) {
                range.push(start);
                start += step;
            }
    
        } else if (typeofStart == "string") {
    
            if (start.length != 1 || end.length != 1) {
                throw TypeError("Only strings with one character are supported.");
            }
    
            start = start.charCodeAt(0);
            end = end.charCodeAt(0);
    
            while (step > 0 ? end >= start : end <= start) {
                range.push(String.fromCharCode(start));
                start += step;
            }
    
        } else {
            throw TypeError("Only string and number types are supported");
        }
    
        return range;
    
    }
    

    jsFiddle

    Array.range

    var range = function(start, end, step) {
        var range = [];
        var typeofStart = typeof start;
        var typeofEnd = typeof end;
    
        if (step === 0) {
            throw TypeError("Step cannot be zero.");
        }
    
        if (typeofStart == "undefined" || typeofEnd == "undefined") {
            throw TypeError("Must pass start and end arguments.");
        } else if (typeofStart != typeofEnd) {
            throw TypeError("Start and end arguments must be of same type.");
        }
    
        typeof step == "undefined" && (step = 1);
    
        if (end < start) {
            step = -step;
        }
    
        if (typeofStart == "number") {
    
            while (step > 0 ? end >= start : end <= start) {
                range.push(start);
                start += step;
            }
    
        } else if (typeofStart == "string") {
    
            if (start.length != 1 || end.length != 1) {
                throw TypeError("Only strings with one character are supported.");
            }
    
            start = start.charCodeAt(0);
            end = end.charCodeAt(0);
    
            while (step > 0 ? end >= start : end <= start) {
                range.push(String.fromCharCode(start));
                start += step;
            }
    
        } else {
            throw TypeError("Only string and number types are supported");
        }
    
        return range;
    
    }
    
    console.log(range("A", "Z", 1));
    console.log(range("Z", "A", 1));
    console.log(range("A", "Z", 3));
    
    
    console.log(range(0, 25, 1));
    
    console.log(range(0, 25, 5));
    console.log(range(20, 5, 5));
        6
  •  38
  •   Kerem    6 年前

    function range(start, stop, step) {
        var a = [start], b = start;
        while (b < stop) {
            a.push(b += step || 1);
        }
        return a;
    }
    
        7
  •  34
  •   kennebec    14 年前
    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']
    
        8
  •  33
  •   Alireza    7 年前

    range()

    function numberRange (start, end) {
      return new Array(end - start).fill().map((d, i) => i + start);
    }
    

    numberRange(5, 10); //[5, 6, 7, 8, 9]
    

    function alphabetRange (start, end) {
      return new Array(end.charCodeAt(0) - start.charCodeAt(0)).fill().map((d, i) => String.fromCharCode(i + start.charCodeAt(0)));
    }
    

    alphabetRange('c', 'h'); //["c", "d", "e", "f", "g"]
    
        9
  •  23
  •   Community CDub    8 年前

    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));

    • range(5,10) // [5, 6, 7, 8, 9, 10]
    • range(10,5) // [10, 9, 8, 7, 6, 5]
    • range(10,2,2) // [10, 8, 6, 4, 2]
    • range(5,10,0,-1) // [6, 7, 8, 9] not 5,10 themselves
    • range(5,10,0,1) // [4, 5, 6, 7, 8, 9, 10, 11]
    • range(5,10,0,-2) // [7, 8]
    • range(10,0,2,2) // [12, 10, 8, 6, 4, 2, 0, -2]


    • (step || 1) step 1
    • (Math.abs(end - start) + ((offset || 0) * 2)) / (step || 1) + 1)
    • new Array(length).fill(0); check here
    • [0,0,0,..] Array.map(function() {})
    • var direction = start < end ? 1 : 0; start end
    • startingPoint stepSize index
        10
  •  22
  •   Klesun Gian Marco    9 年前
    var range = (l,r) => new Array(r - l).fill().map((_,k) => k + l);
    
        11
  •  16
  •   c.P.u1    10 年前

    spread operator

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

    range(10, 15);
    [ 10, 11, 12, 13, 14, 15 ]
    
        12
  •  16
  •   Mike Dinescu    7 年前
        13
  •  11
  •   yoniLavi qwwqwwq    10 年前

    Checkout the jsperf comparison

    function range(lowEnd,highEnd){
        var arr = [],
        c = highEnd - lowEnd + 1;
        while ( c-- ) {
            arr[c] = highEnd--
        }
        return arr;
    }
    range(0,31);
    

        14
  •  10
  •   Rick Hitchcock    11 年前

    function r(a,b){return a>b?[]:[a].concat(r(++a,b))}
    

    function r(a,b){return (a<b?[a,b].concat(r(++a,--b)):a>b?[]:[a]).sort(function(a,b){return a-b})}
    
        15
  •  9
  •   Paolo Moretti    8 年前

    lodash Undescore.js range

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

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

    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;
      }
    }
    

    for (let i of range(1, oneZillion)) {
      console.log(i);
    }
    
        16
  •  8
  •   Sasha Zezulinsky    10 年前

    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]
    

    >>> range(-4,2)
    [-4, -3, -2, -1, 0, 1]
    
        17
  •  8
  •   dietary-wheevil    8 年前

    Array.from()

    const getRange = (start, stop) => Array.from(
      new Array((stop - start) + 1),
      (_, i) => i + start
    );
    
        18
  •  8
  •   Hero Qu    8 年前

    Paolo Moretti answer with ES6 generators

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

    const RANGE_ITER = (a,b) => (function*(x,y){
      while (x++< y) yield x;
    })(a,b);
    
    for (let n of RANGE_ITER(3,7)){
      console.log(n);
    }
    
        19
  •  7
  •   user642922    11 年前

    range

    function range(start, end) {
        var total = [];
    
        if (!end) {
            end = start;
            start = 0;
        }
    
        for (var i = start; i < end; i += 1) {
            total.push(i);
        }
    
        return total;
    }
    
    console.log(range(10)); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
    console.log(range(0, 10)); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    console.log(range(5, 10)); // [5, 6, 7, 8, 9] 
    
        20
  •  6
  •   Janus Troelsen    8 年前

    Harmony generators supported by all browsers except IE11

    var take = function (amount, generator) {
        var a = [];
    
        try {
            while (amount) {
                a.push(generator.next());
                amount -= 1;
            }
        } catch (e) {}
    
        return a;
    };
    
    var takeAll = function (gen) {
        var a = [],
            x;
    
        try {
            do {
                x = a.push(gen.next());
            } while (x);
        } catch (e) {}
    
        return a;
    };
    
    var range = (function (d) {
        var unlimited = (typeof d.to === "undefined");
    
        if (typeof d.from === "undefined") {
            d.from = 0;
        }
    
        if (typeof d.step === "undefined") {
            if (unlimited) {
                d.step = 1;
            }
        } else {
            if (typeof d.from !== "string") {
                if (d.from < d.to) {
                    d.step = 1;
                } else {
                    d.step = -1;
                }
            } else {
                if (d.from.charCodeAt(0) < d.to.charCodeAt(0)) {
                    d.step = 1;
                } else {
                    d.step = -1;
                }
            }
        }
    
        if (typeof d.from === "string") {
            for (let i = d.from.charCodeAt(0); (d.step > 0) ? (unlimited ? true : i <= d.to.charCodeAt(0)) : (i >= d.to.charCodeAt(0)); i += d.step) {
                yield String.fromCharCode(i);
            }
        } else {
            for (let i = d.from; (d.step > 0) ? (unlimited ? true : i <= d.to) : (i >= d.to); i += d.step) {
                yield i;
            }
        }
    });
    

    take

    take(10, range( {from: 100, step: 5, to: 120} ) )

    [100, 105, 110, 115, 120]

    to

    take(10, range( {from: 100, step: 5} ) )

    [100, 105, 110, 115, 120, 125, 130, 135, 140, 145]

    from

    takeAll( range( {to: 5} ) )

    [0, 1, 2, 3, 4, 5]

    takeAll( range( {to: 500, step: 100} ) )

    [0, 100, 200, 300, 400, 500]

    takeAll( range( {from: 'z', to: 'a'} ) )

    ["z", "y", "x", "w", "v", "u", "t", "s", "r", "q", "p", "o", "n", "m", "l", "k", "j", "i", "h", "g", "f", "e", "d", "c", "b", "a"]

        21
  •  6
  •   Evan Carroll    6 年前

    range(start,end,step)

    range()

    function * range ( start, end, step = 1 ) {
      let state = start;
      while ( state < end ) {
        yield state;
        state += step;
      }
      return;
    };
    

    Array.from()

    const generate_array = (start,end,step) =>
      Array.from( range(start,end,step) );
    

    const array1 = generate_array(1,10,2);
    const array1 = generate_array(1,7);
    

    for ( const i of range(1, Number.MAX_SAFE_INTEGER, 7) ) {
      console.log(i)
    }
    

        22
  •  5
  •   Bhargav Rao rlgjr    10 年前
        23
  •  5
  •   jhaskell    10 年前

    function range(start, stop)
    {
        var array = [];
    
        var length = stop - start; 
    
        for (var i = 0; i <= length; i++) { 
            array[i] = start;
            start++;
        }
    
        return array;
    }
    
    console.log(range(1, 7));  // [1,2,3,4,5,6,7]
    console.log(range(5, 10)); // [5,6,7,8,9,10]
    console.log(range(-2, 3)); // [-2,-1,0,1,2,3]
    

        24
  •  5
  •   John Swindin    7 年前

    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.
    

        25
  •  4
  •   Bob Baxley    9 年前

    https://github.com/mbostock/d3/wiki/Arrays#d3_range

    d3.range(10)
    // returns [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
        26
  •  4
  •   Anona112    8 年前

    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(stop<start)step=-Math.abs(step)
    

    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)
    }
    

        27
  •  4
  •   Golo Roden    7 年前

    bereich

    console.log(...bereich(1, 10));
    // => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
    
    const numbers = Array.from(bereich(1, 10));
    // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
    
    for (const number of bereich(1, 10)) {
      // ...
    }
    

    min max 1

        28
  •  3
  •   nha    9 年前

    // [begin, end[
    const range = (b, e) => Array.apply(null, Array(e - b)).map((_, i) => {return i+b;});
    

    const range = (b, e) => Array.apply(null, Array(Math.abs(e - b))).map((_, i) => {return b < e ? i+b : b-i;});
    
        29
  •  3
  •   Michael Plautz    8 年前

    Array.prototype.map.call(' '.repeat(1 + upper - lower), (v, i) => i + lower)
    

    Array.prototype.map.call(' '.repeat(1 + upper.codePointAt() - lower.codePointAt()), (v, i) => String.fromCodePoint(i + lower.codePointAt()));
    
        30
  •  3
  •   Grant Miller    7 年前

    const range = Array.from(Array(size)).map((el, idx) => idx+1).slice(begin, end);