在 Javascript/jQuery 中创建包含两个数字之间的所有整数的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8069315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create array of all integers between two numbers, inclusive, in Javascript/jQuery
提问by 40 Degree Day
Say I have the following checkbox:
假设我有以下复选框:
<input type="checkbox" value="1-25" />
To get the two numbers that define the boundaries of range I'm looking for, I use the following jQuery:
为了获得定义我正在寻找的范围边界的两个数字,我使用以下 jQuery:
var value = $(this).val();
var lowEnd = Number(value.split('-')[0]);
var highEnd = Number(value.split('-')[1]);
How do I then create an array that contains all integers between lowEnd
and highEnd
, including lowEnd
and highEnd
themselves? For this specific example, obviously, the resulting array would be:
然后我如何创建一个包含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]
回答by Ben
var list = [];
for (var i = lowEnd; i <= highEnd; i++) {
list.push(i);
}
回答by m59
In JavaScript ES6:
在 JavaScript ES6 中:
function range(start, end) {
return Array(end - start + 1).fill().map((_, idx) => start + idx)
}
var result = range(9, 18); // [9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
console.log(result);
For completeness, here it is with an optional step
parameter.
为了完整起见,这里有一个可选step
参数。
function range(start, end, step = 1) {
const len = Math.floor((end - start) / step) + 1
return Array(len).fill().map((_, idx) => start + (idx * step))
}
var result = range(9, 18, 0.83);
console.log(result);
I would use range-inclusive
from npmin an actual project. It even supports backwards steps, so that's cool.
我会在实际项目中使用range-inclusive
from npm。它甚至支持倒退,所以很酷。
回答by Abdennour TOUMI
ES6 :
ES6:
console.log(
Array.from({length:10},(v,k)=>k+1)
)
回答by ErichBSchulz
I highly recommend underscore or lo-dash libraries:
我强烈推荐下划线或 lo-dash 库:
http://underscorejs.org/#range
http://underscorejs.org/#range
(Almost completely compatible, apparently lodash runs quicker but underscore has better doco IMHO)
(几乎完全兼容,显然 lodash 运行得更快但下划线有更好的 doco 恕我直言)
_.range([start], stop, [step])
Both libraries have bunch of very useful utilities.
这两个库都有一堆非常有用的实用程序。
回答by Pavel Podlipensky
My version of the loop ;)
我的循环版本;)
var lowEnd = 1;
var highEnd = 25;
var arr = [];
while(lowEnd <= highEnd){
arr.push(lowEnd++);
}
回答by cocco
fastest way
最快的方式
- while-- is faster on most browsers
- direct setting a variable is faster than push
- while-- 在大多数浏览器上更快
- 直接设置变量比推送快
function:
功能:
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--}
EDIT
编辑
readable version
可读版本
var arr = [],
c = highEnd - lowEnd + 1;
while ( c-- ) {
arr[c] = highEnd--
}
Demo
演示
FOR THE DOWNVOTERS
对于投票者
performance
表现
http://jsperf.com/for-push-while-set/2
http://jsperf.com/for-push-while-set/2
faster in ie and 3x faster in firefox
在 ie 中更快,在 Firefox 中快 3 倍
only on aipad air the for loop is a little faster.
仅在 aipad air 上 for 循环会快一点。
tested on win8, osx10.8, ubuntu14.04, ipad, ipad air, ipod;
在 win8、osx10.8、ubuntu14.04、ipad、ipad air、ipod 上测试;
with chrome,ff,ie,safari,mobile safari.
使用 chrome,ff,ie,safari,mobile safari。
i would like to see the performance on older ie browsers where the for loop isn't that optimized!
我想看看在旧的 ie 浏览器上的性能,其中 for 循环没有优化!
回答by david.barkhuizen
function range(j, k) {
return Array
.apply(null, Array((k - j) + 1))
.map(function(_, n){ return n + j; });
}
this is roughly equivalent to
这大致相当于
function range(j, k) {
var targetLength = (k - j) + 1;
var a = Array(targetLength);
var b = Array.apply(null, a);
var c = b.map(function(_, n){ return n + j; });
return c;
}
breaking it down:
分解它:
var targetLength = (k - j) + 1;
var a = Array(targetLength);
this creates a sparse matrix of the correct nominal length. Now the problem with a sparse matrix is that although it has the correct nominal length, it has no actual elements, so, for
这将创建一个正确标称长度的稀疏矩阵。现在稀疏矩阵的问题是,尽管它具有正确的标称长度,但它没有实际元素,因此,对于
j = 7, k = 13
console.log(a);
gives us
给我们
Array [ <7 empty slots> ]
Then
然后
var b = Array.apply(null, a);
passes the sparse matrix as an argument list to the Array constructor, which produces a dense matrix of (actual) length targetLength, where all elements have undefined value. The first argument is the 'this' value for the the array constructor function execution context, and plays no role here, and so is null.
将稀疏矩阵作为参数列表传递给 Array 构造函数,它生成一个(实际)长度为 targetLength 的密集矩阵,其中所有元素都有未定义的值。第一个参数是数组构造函数执行上下文的“this”值,在这里没有任何作用,因此为空。
So now,
所以现在,
console.log(b);
yields
产量
Array [ undefined, undefined, undefined, undefined, undefined, undefined, undefined ]
finally
最后
var c = b.map(function(_, n){ return n + j; });
makes use of the fact that the Array.map function passes: 1. the value of the current element and 2. the index of the current element, to the map delegate/callback. The first argument is discarded, while the second can then be used to set the correct sequence value, after adjusting for the start offset.
利用 Array.map 函数将:1. 当前元素的值和 2. 当前元素的索引传递给映射委托/回调的事实。第一个参数被丢弃,而第二个参数可用于在调整起始偏移后设置正确的序列值。
So then
那么
console.log(c);
yields
产量
Array [ 7, 8, 9, 10, 11, 12, 13 ]
回答by drjorgepolanco
If the start is always less than the end, we can do:
如果开始总是小于结束,我们可以这样做:
function range(start, end) {
var myArray = [];
for (var i = start; i <= end; i += 1) {
myArray.push(i);
}
return myArray;
};
console.log(range(4, 12)); // → [4, 5, 6, 7, 8, 9, 10, 11, 12]
If we want to be able to take a third argument to be able to modify the step used to build the array, and to make it work even though the start is greater than the end:
如果我们希望能够采用第三个参数来修改用于构建数组的步骤,并使其即使开始大于结束也能工作:
function otherRange(start, end, step) {
otherArray = [];
if (step == undefined) {
step = 1;
};
if (step > 0) {
for (var i = start; i <= end; i += step) {
otherArray.push(i);
}
} else {
for (var i = start; i >= end; i += step) {
otherArray.push(i);
}
};
return otherArray;
};
console.log(otherRange(10, 0, -2)); // → [10, 8, 6, 4, 2, 0]
console.log(otherRange(10, 15)); // → [10, 11, 12, 13, 14, 15]
console.log(otherRange(10, 20, 2)); // → [10, 12, 14, 16, 18, 20]
This way the function accepts positive and negative steps and if no step is given, it defaults to 1.
通过这种方式,函数接受正步和负步,如果没有给出步,则默认为 1。
回答by Sergei Panfilov
My five cents:
我的五分钱:
Both directionarray of integers function.
两个方向的整数数组函数。
When range(0, 5)become [0, 1, 2, 3, 4, 5]
.
当range(0, 5)变为[0, 1, 2, 3, 4, 5]
.
And range(5, 0)become [5, 4, 3, 2, 1, 0]
.
而range(5, 0)变为[5, 4, 3, 2, 1, 0]
.
Based on thisanswer.
基于这个答案。
function range(start, end) {
const isReverse = (start > end);
const targetLength = isReverse ? (start - end) + 1 : (end - start ) + 1;
const arr = new Array(targetLength);
const b = Array.apply(null, arr);
const result = b.map((discard, n) => {
return (isReverse) ? n + end : n + start;
});
return (isReverse) ? result.reverse() : result;
}
P.S. For use in real life you should also check args for isFinite()
and isNaN()
.
PS 要在现实生活中使用,您还应该检查isFinite()
和 的参数isNaN()
。
回答by Igor
function createNumberArray(lowEnd, highEnd) {
var start = lowEnd;
var array = [start];
while (start < highEnd) {
array.push(start);
start++;
}
}