Jaanus Jaanus - 20 days ago 6
Javascript Question

Switch on ranges of integers in JavaScript

I want to do something like this

switch (this.dealer) {
case 1-4:
// Do something.
break;
case 5-8:
// Do something.
break;
case 9-11:
// Do something.
break;
default:
break;
}


What is the right syntax for this? Is it possible in JavaScript?

So
this.dealer
is an integer, and if it's between those values, do something.

Answer

Here is another way I figured it out:

var x = this.dealer;
switch (true) {
    case (x < 5):
        alert("less than five");
        break;
    case (x > 4 && x < 9):
        alert("between 5 and 8");
        break;
    case (x > 8 && x < 12):
        alert("between 9 and 11");
        break;
    default:
        alert("none");
        break;
}
Comments