JQuery Using ranges in switch enclosures?

Switching cases are usually similar to

Monday: Tuesday: Wednesday: etc. 

I would like to use ranges.

 from 1-12: from 13-19: from 20-21: from 22-30: 

Is it possible? By the way, I am using javascript / jquery.

+6
javascript switch-statement
source share
4 answers

you can try to abuse disconnecting the switch through behavior

 var x = 5; switch (x) { case 1: case 2: case 3: case 4: ... break; case 13: case 14: case 15: ... break; ... } 

which is very verbose

or you can try this

 function checkRange(x, n, m) { if (x >= n && x <= m) { return x; } else { return !x; } } var x = 5; switch (x) { case checkRange(x, 1, 12): //do something break; case checkRange(x, 13, 19): ... } 

it gives you the behavior you would like. The reason I am returning !x to else checkRange is to prevent the problem when you pass undefined to the switch statement. if your function returns undefined (like jdk example) and you pass undefined to the switch, then the first case will be executed. !x guaranteed not equal to x in any equality test, since the switch statement chooses which case to execute.

+14
source share

Late to the party, but, finding the answer to the same question, I came across this topic. I am currently using a switch, but in a different way. For example:

 switch(true) { case (x >= 1 && x <= 12): //do some stuff break; case (x >= 13 && x <= 19): //do some other stuff break; default: //do default stuff break; } 

It seems to me that this is a lot easier to read than a bunch of IF statements.

+7
source share

You can make interesting kludges. For example, to test a number against a range using a JavaScript switch, you could write a custom function. Basically, the function test a gives the value n and returns it if it is in range. Otherwise, an undefined or other dummy value is returned.

 <script> // Custom Checking Function.. function inRangeInclusive(start, end, value) { if (value <= end && value >= start) return value; // return given value return undefined; } // CODE TO TEST FUNCTION var num = 3; switch(num) { case undefined: //do something with this 'special' value returned by the inRangeInclusive(..) fn break; case inRangeInclusive(1, 10, num): alert('in range'); break; default: alert('not in range'); break; } </script> 

This works in Google Chrome. I have not tested other browsers.

+1
source share

No, you need to use the if / else if series. JavaScript is not a fantasy. (Not many languages.)

0
source share

All Articles