In VB if I wanted to bine a case statment it would look like this
Select (somevalue)
Case 1, 2, 3:
Do Something
End Select
In C# and Javascript
switch (someValue) {
case 1:
case 2:
case 3:
//dosomething
break;
}
However this runs without errors in Javascript
switch (someValue) {
case 1, 2, 3:
break;
}
But does not do what is expected. What is it actually doing?
The reason I ask is because if I hover over the 1, 2, or 3 in firebug it specifies the watch as false. So clearly the code is evaluating but what is it evaluating.
In VB if I wanted to bine a case statment it would look like this
Select (somevalue)
Case 1, 2, 3:
Do Something
End Select
In C# and Javascript
switch (someValue) {
case 1:
case 2:
case 3:
//dosomething
break;
}
However this runs without errors in Javascript
switch (someValue) {
case 1, 2, 3:
break;
}
But does not do what is expected. What is it actually doing?
The reason I ask is because if I hover over the 1, 2, or 3 in firebug it specifies the watch as false. So clearly the code is evaluating but what is it evaluating.
Share Improve this question asked Dec 15, 2010 at 19:38 John HartsockJohn Hartsock 86.9k23 gold badges135 silver badges146 bronze badges 1-
2
1, 2, 3
is an expression that evaluates to3
. – Gabe Commented Dec 15, 2010 at 19:42
3 Answers
Reset to default 5The Javascript ma operator evaluates both its operands in left to right order, returning the rightmost. So, you essentially wrote
switch (someValue) {
case 3:
break;
}
You could also use:
switch(true) {
case (somevalue <= 3): /* action if <= 3 */ break;
case (somevalue <= 6): /* action if <= 6 */ break;
//[etc]
default: 'no action'
}
Just for fun: to be able to pare a number against multiple values a Number extension may e in handy:
Number.prototype.In = function(){
var i = -1, args = arguments;
while (++i<args.length){
//use float for all numbers
if (parseFloat(this) === parseFloat(args[i])){
return true;
}
}
return false;
};
and then your switch bees:
switch(true) {
case somevalue.In(1,2,3): /* action if 1,2,3 */ break;
case somevalue.In(6,10,14): /* action if 6,10,14 */ break;
//[etc]
default: 'no action'
}
See also O'Reilly - chapter on switch
MDarwi beat me to it, nonetheless he nailed it,
<script type="text/javascript">
var x = 5;
switch (x)
{
case 5, 6, 7:
document.write("<b>This should work on 5, 6 or 7.</b>");
break;
case 0:
document.write("<b>This should work on 0.</b>");
break;
}
</script>
..writes the first case only when x == 7.