Monday, June 3, 2024
102
rated 0 times [  108] [ 6]  / answers: 1 / hits: 99423  / 14 Years ago, thu, august 12, 2010, 12:00:00

I'm trying to create a switch statement but I can't seem to be able to use an expression that gets evaluated (rather than a set string/integer). I can easily do this with if statements but case should hopefully be faster.



I'm trying the following



function reward(amount) {
var $reward = $(#reward);
switch (amount) {
case (amount >= 7500 && amount < 10000):
$reward.text(Play Station 3);
break;
case (amount >= 10000 && amount < 15000):
$reward.text(XBOX 360);
break;
case (amount >= 15000):
$reward.text(iMac);
break;
default:
$reward.text(No reward);
break;
}
}


Am i missing something obvious or is this not possible? Google hasn't been friendly in this case.



Any help/pointers appreciated



M


More From » switch-statement

 Answers
17

amount is a number, but the expressions in the case clauses only evaluate to booleans; the values will never match.


You could always do


switch (true) {
case (amount >= 7500 && amount < 10000):
// Code
break;
case (amount >= 10000 && amount < 15000):
// Code
break;
// etc.
}

It works because the value being matched is now the boolean true, so the code under the first case clause with an expression that evaluates to true will be executed.


It’s kinda “tricky”, I guess, but I see nothing wrong with using it. A simple ifelse statement would probably be more concise, and you’d not have to worry about accidental fall-through. But there it is anyway.


[#95948] Tuesday, August 10, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marquezb

Total Points: 237
Total Questions: 97
Total Answers: 89

Location: Israel
Member since Wed, Apr 14, 2021
3 Years ago
;