Switch on ranges of integers in JavaScript
Here is another way I figured it out:
const x = this.dealer;
switch (true) {
case (x < 5):
alert("less than five");
break;
case (x < 9):
alert("between 5 and 8");
break;
case (x < 12):
alert("between 9 and 11");
break;
default:
alert("none");
break;
}
How can I use ranges in a switch case statement using JavaScript?
You have at least four options:
1. List each case
As shown by LightStyle, you can list each case explicitly:
switch(myInterval){
case 0:
case 1:
case 2:
doStuffWithFirstRange();
break;
case 3:
case 4:
case 5:
doStuffWithSecondRange();
break;
case 6:
case 7:
doStuffWithThirdRange();
break;
default:
doStuffWithAllOthers();
}
2. Use if
/ else if
/ else
If the ranges are large, that gets unwieldy, so you'd want to do ranges. Note that with if...else if...else if
, you don't get to the later ones if an earlier one matches, so you only have to specify the upper bound each time. I'll include the lower bound in /*...*/
for clarity, but normally you would leave it off to avoid introducing a maintenance issue (if you include both boundaries, it's easy to change one and forget to change the other):
if (myInterval < 0) {
// I'm guessing this is an error
}
else if (/* myInterval >= 0 && */ myInterval <= 2){
doStuffWithFirstRange();
}
else if (/* myInterval >= 3 && */ myInterval <= 5) {
doStuffWithSecondRange();
}
else if (/* myInterval >= 6 && */ myInterval <= 7) {
doStuffWithThirdRange();
}
else {
doStuffWithAllOthers();
}
3. Use case
with expressions:
JavaScript is unusual in that you can use expressions in the case
statement, so we can write the if...else if...else if
sequence above as a switch
statement:
switch (true){
case myInterval < 0:
// I'm guessing this is an error
break;
case /* myInterval >= 0 && */ myInterval <= 2:
doStuffWithFirstRange();
break;
case /* myInterval >= 3 && */ myInterval <= 5:
doStuffWithSecondRange();
break;
case /* myInterval >= 6 && */ myInterval <= 7:
doStuffWithThirdRange();
break;
default:
doStuffWithAllOthers();
}
I'm not advocating that, but it is an option in JavaScript, and there are times it's useful. The case
statements are checked in order against the value you give in the switch
. (And again, lower bounds could be omitted in many cases because they would have matched earlier.) Even though the case
s are processed in source-code order, the default
can appear anywhere (not just at the end) and is only processed if either no case
s matched or a case
matched and fell through to the default (didn't have a break
; it's rare you want to do that, but it happens).
4. Use a dispatch map
If your functions all take the same arguments (and that could be no arguments, or just the same ones), another approach is a dispatch map:
In some setup code:
var dispatcher = {
0: doStuffWithFirstRange,
1: doStuffWithFirstRange,
2: doStuffWithFirstRange,
3: doStuffWithSecondRange,
4: doStuffWithSecondRange,
5: doStuffWithSecondRange,
6: doStuffWithThirdRange,
7: doStuffWithThirdRange
};
Then instead of the switch:
(dispatcher[myInterval] || doStuffWithAllOthers)();
That works by looking up the function to call on the dispatcher
map, defaulting to doStuffWithAllOthers
if there's no entry for that specific myInterval
value using the curiously-powerful ||
operator, and then calling it.
You can break that into two lines to make it a bit clearer:
var f = dispatcher[myInterval] || doStuffWithAllOthers;
f();
I've used an object for maximum flexibility. You could define dispatcher
like this with your specific example:
var dispatcher = [
/* 0-2 */
doStuffWithFirstRange,
doStuffWithFirstRange,
doStuffWithFirstRange,
/* 3-5 */
doStuffWithSecondRange,
doStuffWithSecondRange,
doStuffWithSecondRange,
/* 6-7 */
doStuffWithThirdRange,
doStuffWithThirdRange
];
...but if the values aren't contiguous numbers, it's much clearer to use an object instead.
Javascript -Switch Ranges on Floating Point Numbers
Don't use switch
, use if
/else
.
if (average > 1 && average <= 1.5) {
// do something
} else if (average > 0.5 && average <= 1) {
// do something
} else if (average > 0 && average <= 0.5) {
// do something
}
Switch Statement with range value
switch statements don't work like that. Your second case is checked like this: if (percent == (percent > 10 && percent < 20)) ...
, which will not yield the desired result.
You could use an if / elseif / else construct:
if (percent === 0) {
widthbytes = 0;
} else if (percent > 10 && percent < 20 {
widthbytes = 16;
} else if (percent >= 20 && percent < 30 {
widthbytes = 30;
} else {
widthbytes = 0;
}
Or you could use a function that turns the ranges into constants:
function getRange(percent) {
return Math.floor(percent/10);
}
switch(getRange(percent)) {
case 10:
widthbytes = 16;
break;
case 20:
widthbytes = 30;
break;
default:
widthbytes = 0;
}
Note that to get a cleaner implementation i assimilated your original case 0: into the default, since they both do the same thing. If that is not desirable, you need to change the getRange function to no longer return the same range for 0 as for any number between 0 and 10.
JavaScript switch-case statement range
It looks like you have a conditional for choosing either left or right based on size, you could break into so:
$('.list-' + ( listSize <=2 ? 'left' : 'right') ).append('<li>' + searchValue + '</li>');
Javascript Switch Range
Change switch(strength)
to switch(true)
. This should work since you are comparing the results of the case statements to the value true
, not to the value of strength
.
JSFiddle: https://jsfiddle.net/eusw15g9/
See this accepted answer for more info: Expression inside switch case statement
jquery Using ranges in switch cases?
you could try abusing the switch fall through behaviour
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 could 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):
...
}
this gets you the behaviour you would like. The reason i return !x
in the else of checkRange is to prevent the problem of when you pass undefined
into the switch statement. if your function returns undefined
(as jdk's example does) and you pass undefined
into the switch, then the first case will be executed. !x
is guaranteed to not equal x
under any test of equality, which is how the switch statement chooses which case to execute.
Switch or value case
There's actually a nice way to do that, notice that switch(true)
will evaluate each expression.
Not always readable, but nice to know.
const money = 200;
switch (true) {
case money < 10:
console.log('You have $10 or less USD');
break;
case money < 50:
console.log('You have $50 or less USD');
break;
case money < 100:
console.log('You have $100 or less USD');
break;
default:
console.log('You are rich! Over $100');
break;
}
how to use switch case(range of number) in jquery?
You can use just as suggested here
switch (true) {
case (tot>10 && tot<110):
$total.html(tot);
$risk.html('小');
break;
case (tot>110 && tot<310):
$total.html(tot);
$risk.html('大');
break;
}
Related Topics
Using Jquery Hover with HTML Image Map
Decryption of Aes Created with Sjcl.Js in Ruby
How to Listen for Keyboard Open/Close in JavaScript/Sencha
How to Detect Scroll Position of Page Using Jquery
Why Is the Ecc-Dh Symmetric Key of This Site Different from Openssl
Display Spinner While Datatables Table Loads Ruby on Rails
(...()) VS. (...)() in JavaScript Closures
Mixing Jsf El in a JavaScript File
Why Doesn't Decodeuri("A+B") == "A B"
Get Number Days in a Specified Month Using JavaScript
Are Functions in JavaScript Tail-Call Optimized
Template Language That Works on Both Server and Client
Rails 5 - Turbolinks 5,Some Js Not Loaded on Page Render
Uncaught Referenceerror: Reactdom Is Not Defined