假设我有以下复选框:

<input type="checkbox" value="1-25" />

为了得到定义我正在寻找的范围边界的两个数字,我使用下面的jQuery:

var value = $(this).val();
var lowEnd = Number(value.split('-')[0]);
var highEnd = Number(value.split('-')[1]);

然后,我如何创建一个包含lowEnd和highEnd之间的所有整数的数组,包括lowEnd和highEnd本身?对于这个特定的例子,显然,结果数组将是:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]

当前回答

您可以设计一个range方法,使“从”数增加所需的数量,直到达到“到”数。 这个例子将“计数”向上或向下,这取决于from比to大还是比to小。

Array.range= function(from, to, step){
    if(typeof from== 'number'){
        var A= [from];
        step= typeof step== 'number'? Math.abs(step):1;
        if(from> to){
            while((from -= step)>= to) A.push(from);
        }
        else{
            while((from += step)<= to) A.push(from);
        }
        return A;
    }   
}

如果你想步进一个小数:Array.range(0,1,01) 您将需要截断任何浮点不精确的值。 否则你会返回类似的数字 0.060000000000000005而不是。06。

这给另一个版本增加了一点开销,但对于整数或十进制步骤是正确的。

Array.range= function(from, to, step, prec){
    if(typeof from== 'number'){
        var A= [from];
        step= typeof step== 'number'? Math.abs(step):1;
        if(!prec){
            prec= (from+step)%1? String((from+step)%1).length+1:0;
        }
        if(from> to){
            while(+(from -= step).toFixed(prec)>= to) A.push(+from.toFixed(prec));
        }
        else{
            while(+(from += step).toFixed(prec)<= to) A.push(+from.toFixed(prec));
        }
        return A;
    }   
}

其他回答

ES6:

使用Array.from (docs here):

console.log ( Array.from({长度:5},(v, k) = > k + 1) )

在JavaScript ES6中:

函数范围(start, end) { 返回Array(end - start + 1).fill()。Map ((_, idx) => start + idx) } Var结果= range(9,18);// [9,10,11,12,13,14,15,16,17,18] console.log(结果);

为了完整起见,这里有一个可选的step参数。

函数范围(start, end, step = 1) { const len =数学。楼层((结束-开始)/台阶)+ 1 返回数组(len) .fill()。Map ((_, idx) => start + (idx * step)) } Var结果= range(9,18,0.83); console.log(结果);

我会在实际项目中使用npm的range-inclusive。它甚至支持后退,这很酷。

最快的方式

而——在大多数浏览器上更快 直接设置变量比推设置快

功能:

var x=function(a,b,c,d){d=[];c=b-a+1;while(c--){d[c]=b--}return d},

theArray=x(lowEnd,highEnd);

or

var arr=[],c=highEnd-lowEnd+1;
while(c--){arr[c]=highEnd--}

编辑

可读版本

var arr = [],
c = highEnd - lowEnd + 1;
while ( c-- ) {
 arr[c] = highEnd--
}

Demo

http://jsfiddle.net/W3CUn/

对于持悲观态度的选民

性能

http://jsperf.com/for-push-while-set/2

ie更快,firefox快3倍

只有在aipad air上,for循环速度略快。

在win8, osx10.8, ubuntu14.04, ipad, ipad air, ipod上测试;

chrome,ff,即,safari,移动safari。

我希望看到旧ie浏览器的性能,其中for循环没有优化!

var list = [];
for (var i = lowEnd; i <= highEnd; i++) {
    list.push(i);
}

纯ES6解决方案

受到上面m59的答案的启发,但没有对填充的依赖:

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

你可以这样使用它:

range(3,5)
=> [3, 4, 5]