假设我有以下复选框:

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

当前回答

最快的方式

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

功能:

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循环没有优化!

其他回答

function createNumberArray(lowEnd, highEnd) {
    var start = lowEnd;
    var array = [start];
    while (start < highEnd) {
        array.push(start);
        start++;
    }
} 

我强烈推荐下划线或低破折号库:

http://underscorejs.org/#range

(几乎完全兼容,显然lodash运行更快,但下划线有更好的doco恕我直言)

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

这两个库都有很多非常有用的实用程序。

var values = $(this).val().split('-'),
    i = +values[0],
    l = +values[1],
    range = [];

while (i < l) {
    range[range.length] = i;
    i += 1;
}

range[range.length] = l;

可能有一个烘干机的方式来做循环,但这是基本的想法。

您可以设计一个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;
    }   
}

将http://minifiedjs.com/添加到答案列表中:)

Code类似于下划线和其他:

var l123 = _.range(1, 4);      // same as _(1, 2, 3)
var l0123 = _.range(3);        // same as _(0, 1, 2)
var neg123 = _.range(-3, 0);   // same as _(-3, -2, -1)
var empty = _.range(2,1);      // same as _()

文档: http://minifiedjs.com/api/range.html

我使用minify .js,因为它解决了我所有的问题,占用空间小,语法容易理解。对我来说,它是一个框架中jQuery, MustacheJS和下划线/SugarJS的替代品。

当然,它不像下划线那样流行。这可能是一些人的担忧。

Minified是由Tim Jansen使用CC-0(公共域)许可证提供的。