Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Switch Statement 2

Status
Not open for further replies.

Mighty

Programmer
Joined
Feb 22, 2001
Messages
1,682
Location
US
Hi Folks,

I'm sure this question has been asked before but the search function was not working for me and I need to find a solution fast.

I need to have a switch statment where each case contains a range of values. Somthing like:

switch(age) {

case < 20:
do something;
break;
case < 20:
do something else;
break;

}

Is there any way to do this with JS?

Mighty
 
I think the value in the case has to be literal and not a range. But you can set code prior to the case statement to set the value used IN the case statement.
Code:
function myFunction(theValue) {
 if (theValue < 20) var age = 1;
 if (theValue > 20) var age = 2;
  switch(age) {
    case 1:
      do something;
      break;
    case 2:
      do something else;
      break;
  }
}
So you do your evaluation up front.
The example is simplistic of course and could just as easily use the same if statment to execute whatever code is needed but this works well with more complex setups though it depends a lot on the data and what you need to accomplish.

It's hard to think outside the box when I'm trapped in a cubicle.
 
[tt]
switch (true) {
case (age<20) :
alert("<20");
break;
case (age>=20) && (age<40) :
alert(">=20 && <40");
break;
case (age>=40) && (age<60) :
alert(">=40 && <60");
break;
default:
alert("default");
break;
}
[/tt]
 
That's a cool way to do it. I had searched around on switch statements and they always had literal values. Had not occured to me that you could evaluate a true/false within the case.


It's hard to think outside the box when I'm trapped in a cubicle.
 
I just do my due, and I get more * than I expect. Thanks!
 
Here's a slightly abbreviated version of tsuji's switch statement. All I did was take out the lower bound age check. For example, if we make it to the second case statement, we know that age is not less than 20. Therefore, age is already shown to be equal or greater than 20 and we just need to check if age is less than 40.

Code:
switch (true) {
    case (age<20) :
        alert("<20");
        break;
    case (age<40) :
        alert(">=20 && <40");
        break;
    case (age<60) :
        alert(">=40 && <60");
        break;
    default:
        alert("default");
        break;
}

Thanks tsuji for showing the correct syntax for a true/false case statement in javascript. I tried unsuccessfully several times to translate from VBA, DB2, and ColdFusion with no luck. It seems pretty obvious now that I see an example!

- Larry
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top