JavaScript是否有像“range()”这样的方法在提供的范围内生成范围?

时间:2010-10-09 02:37:30

标签: javascript arrays

在PHP中,你可以做...

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

也就是说,有一个函数可以通过传递上限和下限来获取一系列数字或字符。

本机有什么内置的JavaScript吗?如果没有,我将如何实施?

69 个答案:

答案 0 :(得分:993)

数字

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

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

没有库的旧非es6浏览器:

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

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

感谢。

(ES6归功于nils petersohn和其他评论者)

答案 1 :(得分:268)

对于数字,您可以使用ES6 Array.from()which works in everything these days,但IE:

除外

更短的版本:

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

更长的版本:

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

创建一个从0到19(包括0和19)的数组。这可以进一步缩短为以下形式之一:

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

答案 2 :(得分:96)

我最喜欢的表格( ES2015

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)

答案 3 :(得分:92)

这是我的2美分:

function range(start, count) {
  return Array.apply(0, Array(count))
    .map((element, index) => index + start);
}

答案 4 :(得分:66)

适用于字符和数字,可选步骤前进或后退。

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

答案 5 :(得分:39)

简单范围功能:

function range(start, stop, step) {
    var a = [start], b = start;
    while (b < stop) {
        a.push(b += step || 1);
    }
    return a;
}

答案 6 :(得分:34)

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']

答案 7 :(得分:34)

我们没有像 PHP 这样的range()函数

好的,,所以我们需要创建一个很容易的函数,我为您编写几个单行函数,并将它们分开为数字字母,如下所示:

数字

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

并称之为:

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

Alphabets

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"]

答案 8 :(得分:23)

方便功能来执行此操作,运行下面的代码段

&#13;
&#13;
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));
&#13;
&#13;
&#13;

这是如何使用它

范围(开始,结束,步骤= 1,偏移= 0);

  • 包含 - 转发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
  • offset - 展开range(5,10,0,1) // [4, 5, 6, 7, 8, 9, 10, 11]
  • offset - 收缩range(5,10,0,-2) // [7, 8]
  • 步骤 - 展开range(10,0,2,2) // [12, 10, 8, 6, 4, 2, 0, -2]

希望你觉得它很有用。

以下是它的工作原理。

基本上我首先计算结果数组的长度,然后在该长度上创建一个零填充数组,然后用所需的值填充

  • (step || 1) =&gt;其他类似的意思是使用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我们需要向后移动。我的意思是从0到5,反之亦然
  • 每次迭代,startingPoint + stepSize * index都会为我们提供所需的价值

答案 9 :(得分:22)

var range = (l,r) => new Array(r - l).fill().map((_,k) => k + l);

答案 10 :(得分:16)

标准Javascript没有内置函数来生成范围。一些javascript框架添加了对这些功能的支持,或者正如其他人指出的那样,你可以随时使用自己的功能。

如果您想仔细检查,最终资源是ECMA-262 Standard

答案 11 :(得分:16)

使用和声spread operator和箭头功能:

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

示例:

range(10, 15);
[ 10, 11, 12, 13, 14, 15 ]

答案 12 :(得分:11)

对一些不同的范围函数进行了一些研究。 Checkout the jsperf comparison 执行这些功能的不同方法。当然不是一个完美或详尽的清单,但应该有所帮助:)

获胜者是......

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

从技术上讲,它不是firefox上最快的,但是Chrome上的疯狂速度差异(imho)弥补了它。

同样有趣的是,使用这些数组函数的chrome比firefox快多少。 Chrome至少快4或5倍

答案 13 :(得分:10)

一个有趣的挑战是编写最短函数来执行此操作。救援的递归!

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

答案 14 :(得分:9)

您可以使用lodashUndescore.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 ]

在ES6中range可以使用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);
}

答案 15 :(得分:8)

使用ES6生成器的另一个版本(参见很棒的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);
}

答案 16 :(得分:8)

我会编写类似这样的代码:

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]

它的行为类似于Python范围:

>>> range(-4,2)
[-4, -3, -2, -1, 0, 1]

答案 17 :(得分:8)

可以如下创建大量使用ES6的极简主义实现,特别注意Array.from()静态方法:

<td>

答案 18 :(得分:7)

使用这个。它创建一个具有给定值(未定义)的数组,在下面的示例中有 100 个索引,但它不相关,因为在这里您只需要键。它在数组中使用 100 + 1,因为数组总是基于 0 索引。因此,如果要生成 100 个值,则索引从 0 开始;因此最后一个值总是 99 而不是 100。

range(2, 100);

function range(start, end) {
    console.log([...Array(end + 1).keys()].filter(value => end >= value && start <= value ));
}

答案 19 :(得分:7)

这可能不是最好的方法。但是,如果您希望在一行代码中获得一系列数字。例如10-50

Array(40).fill(undefined).map((n, i) => i + 10)

其中40是(结束-开始),而10是开始。这应该返回 [10,11,...,50]

答案 20 :(得分:7)

虽然这不是来自 PHP ,而是来自 Python 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] 

答案 21 :(得分:6)

使用Harmony generatorssupported 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;
        }
    }
});

实施例

<强>取

示例1。

take只能获得尽可能多的

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

返回

[100, 105, 110, 115, 120]

示例2。

to不是必要的

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

返回

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

<强> takeAll

示例3。

from不是必要的

takeAll( range( {to: 5} ) )

返回

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

示例4。

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

返回

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

示例5。

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"]

答案 22 :(得分:6)

range(start,end,step):使用ES6迭代器

您只要求一个上限和下限。 我们也在此处创建一个步骤。

您可以轻松创建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)
}

特别注意事项

答案 23 :(得分:5)

就为给定范围生成数值数组而言,我使用:

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)

...更多范围,使用生成器功能。

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 :(得分:5)

您可以创建自己的 es6 范围版本

# Create the signer recipient model
$signer = new Signer([ # The signer
    'email' => $args['signer_email'], 'name' => $args['signer_name'],
    'recipient_id' => "1", 'routing_order' => "1"
]);

# Create a sign_here tab (field on the document)
$sign_here = new SignHere([ # DocuSign SignHere field/tab
    'anchor_string' => '/sn1/', 'anchor_units' => 'pixels',
    'anchor_y_offset' => '10', 'anchor_x_offset' => '20'
]);

# Add the tabs model (including the sign_here tab) to the signer
# The Tabs object wants arrays of the different field/tab types
$signer->settabs(new Tabs(['sign_here_tabs' => [$sign_here]]));

# Next, create the top level envelope definition and populate it.
$envelope_definition = new EnvelopeDefinition([
    'email_subject' => "Please sign this document sent from the PHP SDK",
    'documents' => [$document],
    # The Recipients object wants arrays for each recipient type
    'recipients' => new Recipients(['signers' => [$signer]]),
    'status' => "sent" # requests that the envelope be created and sent.
]);

答案 26 :(得分:5)

您可以使用lodash函数_.range(10) https://lodash.com/docs#range

答案 27 :(得分:4)

有一个npm模块bereich(“bereich”是德语单词“range”)。它使用现代JavaScript的迭代器,因此您可以通过各种方式使用它,例如:

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)) {
  // ...
}

它还支持降序范围(只需交换minmax),它还支持1以外的其他步骤。

免责声明:我是本单元的作者,所以请尽量回答我的问题。

答案 28 :(得分:4)

d3还具有内置范围功能。见https://github.com/mbostock/d3/wiki/Arrays#d3_range

  

d3.range([start,] stop [,step])

     

生成一个包含算术级数的数组,类似于Python内置范围。此方法通常用于迭代一系列数值或整数值,例如索引到数组中。与Python版本不同,参数不需要是整数,但如果它们是由浮点精度引起的,则结果更可预测。如果省略step,则默认为1.

示例:

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

答案 29 :(得分:4)

使用范围([start,] stop [,step])签名完成ES6实施:

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

如果你有很大的范围,请看Paolo Moretti的发电机方法

答案 30 :(得分:4)

https://stackoverflow.com/a/49577331/8784402

具有增量/步长

最小单线
[...Array(N)].map((_, i) => from + i * step);

示例和其他替代方法

[...Array(10)].map((_, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

Array.from(Array(10)).map((_, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

Array.from(Array(10).keys()).map(i => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

[...Array(10).keys()].map(i => 4 + i * -2);
//=> [4, 2, 0, -2, -4, -6, -8, -10, -12, -14]

Array(10).fill(0).map((_, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

Array(10).fill().map((_, i) => 4 + i * -2);
//=> [4, 2, 0, -2, -4, -6, -8, -10, -12, -14]
范围功能
const range = (from, to, step) =>
  [...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);

range(0, 9, 2);
//=> [0, 2, 4, 6, 8]

// can also assign range function as static method in Array class (but not recommended )
Array.range = (from, to, step) =>
  [...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);

Array.range(2, 10, 2);
//=> [2, 4, 6, 8, 10]

Array.range(0, 10, 1);
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Array.range(2, 10, -1);
//=> []

Array.range(3, 0, -1);
//=> [3, 2, 1, 0]
作为迭代器
class Range {
  constructor(total = 0, step = 1, from = 0) {
    this[Symbol.iterator] = function* () {
      for (let i = 0; i < total; yield from + i++ * step) {}
    };
  }
}

[...new Range(5)]; // Five Elements
//=> [0, 1, 2, 3, 4]
[...new Range(5, 2)]; // Five Elements With Step 2
//=> [0, 2, 4, 6, 8]
[...new Range(5, -2, 10)]; // Five Elements With Step -2 From 10
//=>[10, 8, 6, 4, 2]
[...new Range(5, -2, -10)]; // Five Elements With Step -2 From -10
//=> [-10, -12, -14, -16, -18]

// Also works with for..of loop
for (i of new Range(5, -2, 10)) console.log(i);
// 10 8 6 4 2
仅作为发电机
const Range = function* (total = 0, step = 1, from = 0) {
  for (let i = 0; i < total; yield from + i++ * step) {}
};

Array.from(Range(5, -2, -10));
//=> [-10, -12, -14, -16, -18]

[...Range(5, -2, -10)]; // Five Elements With Step -2 From -10
//=> [-10, -12, -14, -16, -18]

// Also works with for..of loop
for (i of Range(5, -2, 10)) console.log(i);
// 10 8 6 4 2

// Lazy loaded way
const number0toInf = Range(Infinity);
number0toInf.next().value;
//=> 0
number0toInf.next().value;
//=> 1
// ...

从步骤到步骤/增量

使用迭代器
class Range2 {
  constructor(to = 0, step = 1, from = 0) {
    this[Symbol.iterator] = function* () {
      let i = 0,
        length = Math.floor((to - from) / step) + 1;
      while (i < length) yield from + i++ * step;
    };
  }
}
[...new Range2(5)]; // First 5 Whole Numbers
//=> [0, 1, 2, 3, 4, 5]

[...new Range2(5, 2)]; // From 0 to 5 with step 2
//=> [0, 2, 4]

[...new Range2(5, -2, 10)]; // From 10 to 5 with step -2
//=> [10, 8, 6]
使用发电机
const Range2 = function* (to = 0, step = 1, from = 0) {
  let i = 0,
    length = Math.floor((to - from) / step) + 1;
  while (i < length) yield from + i++ * step;
};

[...Range2(5, -2, 10)]; // From 10 to 5 with step -2
//=> [10, 8, 6]

let even4to10 = Range2(10, 2, 4);
even4to10.next().value;
//=> 4
even4to10.next().value;
//=> 6
even4to10.next().value;
//=> 8
even4to10.next().value;
//=> 10
even4to10.next().value;
//=> undefined

对于打字稿

class _Array<T> extends Array<T> {
  static range(from: number, to: number, step: number): number[] {
    return Array.from(Array(Math.floor((to - from) / step) + 1)).map(
      (v, k) => from + k * step
    );
  }
}
_Array.range(0, 9, 1);

https://stackoverflow.com/a/64599169/8784402

单线生成字符列表

const charList = (a,z,d=1)=>(a=a.charCodeAt(),z=z.charCodeAt(),[...Array(Math.floor((z-a)/d)+1)].map((_,i)=>String.fromCharCode(a+i*d)));

console.log("from A to G", charList('A', 'G'));
console.log("from A to Z with step/delta of 2", charList('A', 'Z', 2));
console.log("reverse order from Z to P", charList('Z', 'P', -1));
console.log("from 0 to 5", charList('0', '5', 1));
console.log("from 9 to 5", charList('9', '5', -1));
console.log("from 0 to 8 with step 2", charList('0', '8', 2));
console.log("from α to ω", charList('α', 'ω'));
console.log("Hindi characters from क to ह", charList('क', 'ह'));
console.log("Russian characters from А to Я", charList('А', 'Я'));

对于TypeScript
const charList = (p: string, q: string, d = 1) => {
  const a = p.charCodeAt(0),
    z = q.charCodeAt(0);
  return [...Array(Math.floor((z - a) / d) + 1)].map((_, i) =>
    String.fromCharCode(a + i * d)
  );
};

答案 31 :(得分:3)

您还可以执行以下操作:

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

答案 32 :(得分:3)

这些示例均未进行过测试,没有实现一步的实现,并且没有产生递减值的选项。

export function range(start = 0, end = 0, step = 1) {
    if (start === end || step === 0) {
        return [];
    }

    const diff = Math.abs(end - start);
    const length = Math.ceil(diff / step);

    return start > end
        ? Array.from({length}, (value, key) => start - key * step)
        : Array.from({length}, (value, key) => start + key * step);

}

测试:

import range from './range'

describe('Range', () => {
    it('default', () => {
        expect(range()).toMatchObject([]);
    })

    it('same values', () => {
        expect(range(1,1)).toMatchObject([]);
    })

    it('step=0', () => {
        expect(range(0,1,0)).toMatchObject([]);
    })

    describe('step=1', () => {
        it('normal', () => {
            expect(range(6,12)).toMatchObject([6, 7, 8, 9, 10, 11]);
        })

        it('reversed', () => {
            expect(range(12,6)).toMatchObject([12, 11, 10, 9, 8, 7]);
        })
    })

    describe('step=5', () => {

        it('start 0 end 60', () => {
            expect(range(0, 60, 5)).toMatchObject([0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55]);
        })

        it('reversed start 60 end -1', () => {
            expect(range(55, -1, 5)).toMatchObject([55, 50, 45, 40, 35, 30, 25, 20, 15, 10, 5, 0]);
        })
    })
})

答案 33 :(得分:3)

这是一个很好的简短方法,只用数字在ES6中完成(不知道它的速度比较):

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

答案 34 :(得分:3)

我很惊讶地发现这个帖子并没有看到像我的解决方案(也许我错过了答案),所以在这里。 我在ES6语法中使用了一个简单的范围函数:

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

但它仅在向前计数时起作用(即,开始&lt;结束),所以我们可以在需要时稍微修改它,如下所示:

const range = (b, e) => Array.apply(null, Array(Math.abs(e - b))).map((_, i) => {return b < e ? i+b : b-i;});

答案 35 :(得分:2)

为了在给定数字可能更大的地方工作,我这样写:

function getRange(start, end) {
  return Array.from({
    length: 1 + Math.abs(end - start)
  }, (_, i) => end > start ? start + i : start - i);
}

答案 36 :(得分:2)

对于行为类似于 python sorted 函数的函数,使用这个:

range()

答案 37 :(得分:1)

一种在边界内生成整数数组的递归解决方案。

function intSequence(start, end, n = start, arr = []) {
  return (n === end) ? arr.concat(n)
    : intSequence(start, end, start < end ? n + 1 : n - 1, arr.concat(n));
}

$> intSequence(1, 1)
<- Array [ 1 ]

$> intSequence(1, 3)
<- Array(3) [ 1, 2, 3 ]

$> intSequence(3, -3)
<- Array(7) [ 3, 2, 1, 0, -1, -2, -3 ]

答案 38 :(得分:1)

这也是相反的。

const range = ( a , b ) => Array.from( new Array( b > a ? b - a : a - b ), ( x, i ) => b > a ? i + a : a - i );

range( -3, 2 ); // [ -3, -2, -1, 0, 1 ]
range( 1, -4 ); // [ 1, 0, -1, -2, -3 ]

答案 39 :(得分:1)

我的代码高尔夫同事提出了这个(ES6), 含:

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

非包容性:

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

答案 40 :(得分:1)

保持简单:

// Generator
function* iter(a, b, step = 1) {
  for (let i = b ? a : 0; i < (b || a); i += step) {
    yield i
  }
}

const range = (a, b, step = 1) =>
  typeof a === 'string'
    ? [...iter(a.charCodeAt(), b.charCodeAt() + 1)].map(n => String.fromCharCode(n))
    : [...iter(a, b, step)]

range(4) // [0, 1, 2, 3]
range(1, 4) // [1, 2, 3]
range(2, 20, 3) // [2, 5, 8, 11, 14, 17]
range('A', 'C') // ['A', 'B', 'C']

答案 41 :(得分:1)

// range()              0..10, step=1
// range(max)           0..max, step=1
// range(min,max)       min..max, step=1
// range(min,step,max)  min..max, step=step
// Use:
// console.log(...range(3));
// Array.from(range(5))
// [...range(100)]
// for (const v of range(1,10)) { ... 

function* range(...args) {
    let [min, step, max] = {
        0: [0, 1, 10],
        1: [0, args[0] >= 0 ? 1 : -1, args[0]],
        2: [args[0], args[1] >= args[0] ? 1 : -1, args[1]],
        3: args,
    }[args.length] || [];
    if (min === undefined) throw new SyntaxError("Too many arguments");
    let x = min;
    while (step >= 0 ? x < max : x > max) {
        yield x;
        x += step
    }
}
console.log(...range());      // 0 1 2 3 4 5 6 7 8 9
console.log(...range(3));     // 0 1 2
console.log(...range(2, 5));  // 2 3 4
console.log(...range(5, 2));  // 5 4 3
console.log(...range(3, -3)); // 3 2 1 0 -1 -2
console.log(...range(-3, 3)); // -3 -2 -1 0 1 2
console.log(...range(-5, -2));// -5 -4 -3
console.log(...range(-2, -5));// -2 -3 -4

答案 42 :(得分:1)

据我了解:

  • JS的运行时环境不支持尾部调用优化。编写任何递归函数以生成较大范围的内容都会带您到这里。
  • 如果要处理大量数据,创建循环数组可能不是最好的选择。
  • 写大循环会导致事件队列变慢。

function range(start, end, step = 1) {
  const _range = _start => f => {
    if (_start < end) {
      f(_start);
      setTimeout(() => _range(_start + step)(f), 0);
    }
  }

  return {
    map: _range(start),
  };
}

range(0, 50000).map(console.log);

此功能不会引起上述担忧。

答案 43 :(得分:1)

Pythonic风格的方式:

range = (start, end, step) => {
let arr = []
for(let n=start;n<end;n+=(step||1)) arr.push(n)
return arr;
}

答案 44 :(得分:1)

我发现一个JS范围函数等同于PHP中的函数,并且效果非常好here。向前推进&amp;向后,并使用整数,浮点数和字母表!

function range(low, high, step) {
  //  discuss at: http://phpjs.org/functions/range/
  // original by: Waldo Malqui Silva
  //   example 1: range ( 0, 12 );
  //   returns 1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
  //   example 2: range( 0, 100, 10 );
  //   returns 2: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
  //   example 3: range( 'a', 'i' );
  //   returns 3: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
  //   example 4: range( 'c', 'a' );
  //   returns 4: ['c', 'b', 'a']

  var matrix = [];
  var inival, endval, plus;
  var walker = step || 1;
  var chars = false;

  if (!isNaN(low) && !isNaN(high)) {
    inival = low;
    endval = high;
  } else if (isNaN(low) && isNaN(high)) {
    chars = true;
    inival = low.charCodeAt(0);
    endval = high.charCodeAt(0);
  } else {
    inival = (isNaN(low) ? 0 : low);
    endval = (isNaN(high) ? 0 : high);
  }

  plus = ((inival > endval) ? false : true);
  if (plus) {
    while (inival <= endval) {
      matrix.push(((chars) ? String.fromCharCode(inival) : inival));
      inival += walker;
    }
  } else {
    while (inival >= endval) {
      matrix.push(((chars) ? String.fromCharCode(inival) : inival));
      inival -= walker;
    }
  }

  return matrix;
}

这是缩小版:

function range(h,c,b){var i=[];var d,f,e;var a=b||1;var g=false;if(!isNaN(h)&&!isNaN(c)){d=h;f=c}else{if(isNaN(h)&&isNaN(c)){g=true;d=h.charCodeAt(0);f=c.charCodeAt(0)}else{d=(isNaN(h)?0:h);f=(isNaN(c)?0:c)}}e=((d>f)?false:true);if(e){while(d<=f){i.push(((g)?String.fromCharCode(d):d));d+=a}}else{while(d>=f){i.push(((g)?String.fromCharCode(d):d));d-=a}}return i};

答案 45 :(得分:1)

对于具有良好向后兼容性的类似ruby的方法:

range([begin], end = 0)其中beginend是数字

var range = function(begin, end) {
  if (typeof end === "undefined") {
    end = begin; begin = 0;
  }
  var result = [], modifier = end > begin ? 1 : -1;
  for ( var i = 0; i <= Math.abs(end - begin); i++ ) {
    result.push(begin + i * modifier);
  }
  return result;
}

示例:

range(3); //=> [0, 1, 2, 3]
range(-2); //=> [0, -1, -2]
range(1, 2) //=> [1, 2]
range(1, -2); //=> [1, 0, -1, -2]

答案 46 :(得分:1)

没有本地方法。但您可以使用filter的{​​{1}}方法执行此操作。

&#13;
&#13;
Array
&#13;
&#13;
&#13;

答案 47 :(得分:1)

这是我的模仿Python的解决方案。在底部,您可以找到一些如何使用它的示例。它适用于数字,就像Python的range

一样
var assert = require('assert');    // if you use Node, otherwise remove the asserts

var L = {};    // L, i.e. 'list'

// range(start, end, step)
L.range = function (a, b, c) {
    assert(arguments.length >= 1 && arguments.length <= 3);
    if (arguments.length === 3) {
        assert(c != 0);
    }

    var li = [],
        i,
        start, end, step,
        up = true;    // Increasing or decreasing order? Default: increasing.

    if (arguments.length === 1) {
        start = 0;
        end = a;
        step = 1;
    }

    if (arguments.length === 2) {
        start = a;
        end = b;
        step = 1;
    }

    if (arguments.length === 3) {
        start = a;
        end = b;
        step = c;
        if (c < 0) {
            up = false;
        }
    }

    if (up) {
        for (i = start; i < end; i += step) {
            li.push(i);
        }
    } else {
        for (i = start; i > end; i += step) {
            li.push(i);
        }
    }

    return li;
}

示例:

// range
L.range(0) -> []
L.range(1) -> [0]
L.range(2) -> [0, 1]
L.range(5) -> [0, 1, 2, 3, 4]

L.range(1, 5) -> [1, 2, 3, 4]
L.range(6, 4) -> []
L.range(-2, 2) -> [-2, -1, 0, 1]

L.range(1, 5, 1) -> [1, 2, 3, 4]
L.range(0, 10, 2) -> [0, 2, 4, 6, 8]
L.range(10, 2, -1) -> [10, 9, 8, 7, 6, 5, 4, 3]
L.range(10, 2, -2) -> [10, 8, 6, 4]

答案 48 :(得分:1)

ES6

使用 Array.from(文档 here):

const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));

答案 49 :(得分:0)

我刚刚通过ArrayObject.defineProperty上创建了这个polyfill,以创建整数或字符串范围。 Object.defineProperty是创建polyfill的一种更安全的方法。

更安全的填充料

if (!Array.range) {
  Object.defineProperty(Array, 'range', {
    value: function (from, to, step) {
      if (typeof from !== 'number' && typeof from !== 'string') {
        throw new TypeError('The first parameter should be a number or a character')
      }

      if (typeof to !== 'number' && typeof to !== 'string') {
        throw new TypeError('The second parameter should be a number or a character')
      }

      var A = []
      if (typeof from === 'number') {
        A[0] = from
        step = step || 1
        while (from + step <= to) {
          A[A.length] = from += step
        }
      } else {
        var s = 'abcdefghijklmnopqrstuvwxyz'
        if (from === from.toUpperCase()) {
          to = to.toUpperCase()
          s = s.toUpperCase()
        }
        s = s.substring(s.indexOf(from), s.indexOf(to) + 1)
        A = s.split('')
      }
      return A
    }
  })
} else {
  var errorMessage = 'DANGER ALERT! Array.range has already been defined on this browser. '
  errorMessage += 'This may lead to unwanted results when Array.range() is executed.'
  console.log(errorMessage)
}

示例

Array.range(1, 3)

// Return: [1, 2, 3]
Array.range(1, 3, 0.5)

// Return: [1, 1.5, 2, 2.5, 3]
Array.range('a', 'c')

// Return: ['a', 'b', 'c']
Array.range('A', 'C')

// Return: ['A', 'B', 'C']
Array.range(null)
Array.range(undefined)
Array.range(NaN)
Array.range(true)
Array.range([])
Array.range({})
Array.range(1, null)

// Return: Uncaught TypeError: The X parameter should be a number or a character

答案 50 :(得分:0)

Array.from(Array((m - n + 1)), (v, i) => n + i); // m > n and both of them are integers.

答案 51 :(得分:0)

一个可以在任一方向上工作的衬纸:

const range = (a,b)=>Array(Math.abs(a-b)+1).fill(a).map((v,i)=>v+i*(a>b?-1:1));

查看实际情况:

const range = (a,b) => Array(Math.abs(a-b)+1).fill(a).map((v,i)=>v+i*(a>b?-1:1));

console.log(range(1,4));
console.log(range(4,1));

答案 52 :(得分:0)

尚未实现!

使用新的Number.range proposal(阶段1):

[...Number.range(1, 10)]
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

答案 53 :(得分:0)

我个人的最爱:

const range = (start, end) => new Array(end-start+1).map((el, ind) => ind + start);

答案 54 :(得分:0)

这是一个基于@benmcdonald和其他人的简单方法,但不止一行......

let K = [];
for (i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) {
  K.push(String.fromCharCode(i))
};
console.log(K);

答案 55 :(得分:0)

具有定义的硬int的范围有很多答案,但是如果您不知道该步骤,而又希望在中间有多个步骤怎么办?

我写了这段代码来做到这一点。这是不言自明的。

const stepScale = (min, max, numberOfSteps) => {
  const _numberOfSteps = numberOfSteps - 1
  const scaleBy = (max - min) / _numberOfSteps

  const arr = []
  for (let i = 0; i <= _numberOfSteps; i += 1) {
    arr.push(min + scaleBy * i)
  }
  return arr
}

export default stepScale
stepScale(5, 10, 4)
// [5, 6.666666666666667, 8.333333333333334, 10]

https://npm.im/@universalstandard/step-scale的npm上

答案 56 :(得分:0)

您可以使用以下一种语言来使事情简短明了

var start = 4;
var end = 20;
console.log(Array(end - start + 1).fill(start).map((x, y) => x + y));

答案 57 :(得分:0)

这是范围函数的定义,其作用与Python的range类型完全相同,不同之处在于该函数不是惰性的。将它变成发电机应该很容易。

范围构造函数的参数必须为数字。如果省略step参数,则默认为1。如果省略start参数,则默认为0。如果step为零,则会引发错误。

range = (start, stop, step=1) => {
    if(step === 0) throw new Error("range() arg 3 must not be zero");

    const noStart = stop == null;
    stop = noStart ? start : stop;
    start = noStart ? 0 : start;
    const length = Math.ceil(((stop - start) / step));

    return Array.from({length}, (_, i) => (i * step) + start);
}

console.log(range(-10, 10, 2));
//output [Array] [-10,-8,-6,-4,-2,0,2,4,6,8]
console.log(range(10));
// [Array] [0,1,2,3,4,5,6,7,8,9]
console.log(3, 12);
// [Array] [3,4,5,6,7,8,9,10,11]

答案 58 :(得分:0)

这是我用于数字范围的内容:

const rangeFrom0 = end => [...Array(end)].map((_, index) => index);

const rangeExcEnd = (start, step, end) => [...Array(end - start + 1)]
   .map((_, index) => index + start)
   .filter(x => x % step === start % step);

答案 59 :(得分:0)

我更喜欢下面的方式

var range = function(x, y) {
    return Array(y - x+1).fill(x).map((a, b) => {return a+b}).filter(i => i >= x);
};
console.log(range(3, 10));

答案 60 :(得分:0)

我想补充一下我认为非常可调的版本,速度非常快。

docker-compose up --build

如果你想要

,也可以打字
const range = (start, end) => {
    let all = [];
    if (typeof start === "string" && typeof end === "string") {
        // Return the range of characters using utf-8 least to greatest
        const s = start.charCodeAt(0);
        const e = end.charCodeAt(0);
        for (let i = s; i <= e; i++) {
            all.push(String.fromCharCode(i));
        }
    } else if (typeof start === "number" && typeof end === "number") {
        // Return the range of numbers from least to greatest
        for(let i = end; i >= start; i--) {
            all.push(i);
        }
    } else {
        throw new Error("Did not supply matching types number or string.");
    }
    return all;
}
// usage
const aTod = range("a", "d");

受到其他答案的影响。用户现在已经离开了。

答案 61 :(得分:0)

对于信件,他是一个简单的香草JS解决方案,我想出来生成字母范围。它仅用于生成大写或小写字母数组。

function range(first, last) {
    var r = [],
        i = first.charCodeAt(0);
    
    while(i <= last.charCodeAt(0)) {
        r.push(String.fromCharCode(i++));
    }
    
    return r;
}

console.dir(range("a", "f"));
console.dir(range("G", "Z"));

答案 62 :(得分:0)

编码为2010年规格(ya,2016年是ES6发电机)。这是我的看法,可以选择模拟Python的range()函数。

Array.range = function(start, end, step){
    if (start == undefined) { return [] } // "undefined" check

    if ( (step === 0) )  {  return []; // vs. throw TypeError("Invalid 'step' input")
    }  // "step" == 0  check

    if (typeof start == 'number') { // number check
        if (typeof end == 'undefined') { // single argument input
            end = start;
            start = 0;
            step = 1;
        }
        if ((!step) || (typeof step != 'number')) {
          step = end < start ? -1 : 1;
        }

        var length = Math.max(Math.ceil((end - start) / step), 0);
        var out = Array(length);

        for (var idx = 0; idx < length; idx++, start += step) {
          out[idx] = start;
        }

        // Uncomment to check "end" in range() output, non pythonic
        if ( (out[out.length-1] + step) == end ) { // "end" check
            out.push(end)
        }

    } else { 
        // Historical: '&' is the 27th letter: http://nowiknow.com/and-the-27th-letter-of-the-alphabet/
        // Axiom: 'a' < 'z' and 'z' < 'A'
        // note: 'a' > 'A' == true ("small a > big A", try explaining it to a kid! )

        var st = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&'; // axiom ordering

        if (typeof end == 'undefined') { // single argument input
            end = start;
            start = 'a';
        }

        var first = st.indexOf(start);
        var last = st.indexOf(end);

        if ((!step) || (typeof step != 'number')) {
          step = last < first ? -1 : 1;
        }

        if ((first == -1) || (last == -1 )) { // check 'first' & 'last'
            return []
        }

        var length = Math.max(Math.ceil((last - first) / step), 0);
        var out = Array(length);

        for (var idx = 0; idx < length; idx++, first += step) {
          out[idx] = st[first];
        } 

        // Uncomment to check "end" in range() output, non pythonic
        if ( (st.indexOf(out[out.length-1]) + step ) == last ) { // "end" check
            out.push(end)
        }
    }
    return out;
}

示例:

Array.range(5);       // [0,1,2,3,4,5]
Array.range(4,-4,-2); // [4, 2, 0, -2, -4]
Array.range('a','d'); // ["a", "b", "c", "d"]
Array.range('B','y'); // ["B", "A", "z", "y"], different from chr() ordering
Array.range('f');     // ["a", "b", "c", "d", "e", "f"]
Array.range(-5);      // [], similar to python
Array.range(-5,0)     // [-5,-4-,-3-,-2,-1,0]

答案 63 :(得分:0)

如果我们输入[4, 2]之类的内容,我们会将[2, 3, 4]作为输出,我们可以使用它。

function createRange(array) {
  var range = [];
  var highest = array.reduce(function(a, b) {
    return Math.max(a, b);
  });
  var lowest = array.reduce(function(a, b) {
    return Math.min(a, b);
  });
  for (var i = lowest; i <= highest; i++) {
    range.push(i);
  }
  return range;
}

答案 64 :(得分:0)

我在for循环中使用条件三元运算符(尽管没有参数测试)。

function range(start,end,step){
   var resar = [];
   for (var i=start;(step<0 ? i>=end:i<=end); i += (step == undefined ? 1:step)){
       resar.push(i);
     };
   return resar;
};

答案 65 :(得分:0)

解决方案:

//best performance
var range = function(start, stop, step) {
    var a = [start];
    while (start < stop) {
        start += step || 1;
        a.push(start);
    }
    return a;
};

//or
var range = function(start, end) {
    return Array(++end-start).join(0).split(0).map(function(n, i) {
        return i+start
    });
}

答案 66 :(得分:-1)

在Eloquent JavaScript中做了类似这样的练习

function range(start, end, step) {
  var ar = [];
  if (start < end) {
    if (arguments.length == 2) step = 1;
    for (var i = start; i <= end; i += step) {
      ar.push(i);
    }
  }
  else {
    if (arguments.length == 2) step = -1;
    for (var i = start; i >= end; i += step) {
      ar.push(i);
    }
  }
  return ar;
}

答案 67 :(得分:-1)

您可以使用带数组的函数,for循环和Math.random()变量来解决这个问题。 for循环将数字推入数组,该数组将包含您范围内的所有数字。然后Math.random()根据数组的长度随机选择一个。

function randNumInRange(min, max) {
  var range = []
  for(var count = min; count <= max; count++) {
    range.push(count);
  }
  var randNum = Math.floor(Math.random() * range.length);
  alert(range[randNum]);
}

答案 68 :(得分:-3)

function check(){

    var correct=true;

    for(var i=0; i<arguments.length; i++){

    if(typeof arguments[i] != "number"){

    correct=false;  } } return correct; }   

//------------------------------------------

 function range(start,step,end){

  var correct=check(start,step,end);

  if(correct && (step && end)!=0){ 

  for(var i=start; i<=end; i+=step)

  document.write(i+" "); }

  else document.write("Not Correct Data"); }