Switch Case To/between
Is there a way in Javascript to compare one integer with another through switch case structures without using if statements? E.g. switch(integer) { case 1 to 10: break
Solution 1:
You can do some math manipulations.
switch(Math.ceil(integer/10)) {
case1: // Integer is between 1-10break;
case2: // Integer is between 11-20break;
case3: // Integer is between 21-30break;
}
Solution 2:
There is a way, yes. I'm pretty sure I'd use an if/else structure in my own code, but if you're keen to use a switch the following will work:
switch(true) {
caseinteger >= 1 && integer <= 10:
// 1-10break;
caseinteger >= 11 && integer <= 20:
// 11-20break;
caseinteger >= 21 && integer <= 30:
// 21-30break;
}
Of course if you wanted to avoid having to code >= && <=
on every case you could define your own isInRange(num,min,max)
type function to return a boolean and then say:
switch (true) {
caseisInRange(integer,1,10):
// 1-10break;
// etc
}
Solution 3:
As stated in my comment, you can't do that. However, you could define an inRange
function:
function inRange(x,min,max){returnmin<= x && x <=max;
}
and use it together with if - else if
. That should make it quite easy to read:
if(inRange(integer, 1, 10)) {
}
else if(inRange(integer, 11, 20)) {
}
//...
Solution 4:
Posting for "cool" syntax :P
if( integer inrange(0,10)){}elseif( integer inrange(11,20)){}elseif( integer inrange(21,30)){}functionrange(min,max){
var o ={}, i ;
for( i =min; i <=max; ++i ){
o[i]=!0;
}return o;
}
Post a Comment for "Switch Case To/between"