我如何将一个数字与 Javascript 中的一系列数字进行比较?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8944606/
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
How would I compare a number to a range of numbers in Javascript?
提问by Ryan S.
I want to compare a range of numbers against a single number, basically like this in simple terms:
我想将一系列数字与单个数字进行比较,简单来说基本上是这样的:
if X through Y equals Z, then do {}
What would be the proper way to do something like that in Javascript?
在 Javascript 中执行类似操作的正确方法是什么?
CLARIFICATION
澄清
I want to check if any number between X and Y
is equal to Z
我想检查之间的任何数字X and Y
是否等于Z
Edit
编辑
I'm not sure why the down-votes, I had a legitimate question.
我不确定为什么投反对票,我有一个合理的问题。
回答by Daniel Moses
A range doesn't equal a number, do you mean that the number falls within the range?
一个范围不等于一个数字,你的意思是这个数字在这个范围内吗?
if (1 <= Z && Z <= 25 ) {
foo();
}
回答by Jon Newmuis
If you want to determine if Z
is inthe range [X, Y]
, then you can do:
如果要确定是否Z
是在该范围内[X, Y]
,那么你可以这样做:
if (X < Z && Z < Y) {
// do stuff.
}
Otherwise, a range can't equal a number.
否则,范围不能等于数字。
回答by Adam Rackis
To check if elements 1 through 3 are all 1:
要检查元素 1 到 3 是否都是 1:
var arr = [0, 1, 1, 1, 2];
var allOne = arr.slice(1, 4).filter(
function(val) { return val !== 1; }).length === 0;
EDIT
编辑
Even better, thanks to @am not i am
更好的是,感谢 @am not i am
var arr = [0, 1, 1, 1, 2];
var allOne = arr.slice(1, 4).every(function (val) { return val === 1; });
回答by ziesemer
var arr = [...];
var compareRange = function(arr, x, y, z){
for(var i=x; i<=y; i++){
if(arr[i] != z){
return false;
}
}
return true;
};
回答by Tristian
First the range function:
首先是范围函数:
function range(a,b){
var r = [a];
for(var i=a;i<=b;i++){
r.push(i);
}
return r;
}
Now use the function and make the comparison:
现在使用该函数并进行比较:
var a = range(1,6); // Range
var z = 7;
if(a.indexOf(z) > -1){
// Collision !!!
}else{
// No collision, I suppose...
}