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?
CLARIFICATION
I want to check if any number between X and Y
is equal to Z
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?
CLARIFICATION
I want to check if any number between X and Y
is equal to Z
6 Answers
Reset to default 9A range doesn't equal a number, do you mean that the number falls within the range?
if (1 <= Z && Z <= 25 ) {
foo();
}
If you want to determine if Z
is in the range [X, Y]
, then you can do:
if (X < Z && Z < Y) {
// do stuff.
}
Otherwise, a range can't equal a number.
var arr = [...];
var compareRange = function(arr, x, y, z){
for(var i=x; i<=y; i++){
if(arr[i] != z){
return false;
}
}
return true;
};
To check if elements 1 through 3 are all 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
var arr = [0, 1, 1, 1, 2];
var allOne = arr.slice(1, 4).every(function (val) { return val === 1; });
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...
}
I am not sure I have completely understood your question.
I made a function that compares a number n
to a range of numbers between min
and max
. This function returns an integer r
from 1 to 5
n
is less thanmin
,r
= 1n
is equal tomin
,r
= 2n
is betweenmin
andmax
,r
= 3n
is equal tomax
,r
= 4n
is greater thanmax
,r
= 5
function compareToRange(n,min,max){
var r=((n<min)*1+(n==min)*2+((n>min)&&(n<max))*3+(n==max)*4+(n>max)*5);
}
X through Y
are the same number asZ
? SoX
andY
are indices of an array, or something? – user1106925 Commented Jan 20, 2012 at 16:30