(Robert Scheer) writes:
> In VBScript I can use a Select Case statement like that:
> Select Case X
> Case 1 to 10 'X is between 1 and 10
> Case 11,14,16 'X is 11 or 14 or 16
> End Select
JavaScript's syntax is based on that of C, and as in C,
there is no syntactic sugar for switch statements. However,
as in C, omitting the "break;" after a switch case will cause
execution to fall through to the following case. (Opinion is
divided on whether this is a good thing.)
switch (x) {
case 1:
case 2:
case 3:
/* ... */
case 10:
// execute some code for this case
break;
case 11:
case 14:
case 16:
// execute some other code for this thing
break;
default:
// complain
break; // for uniformity
}
In my opinion it is good practice to mark with LOUD COMMENTS
places where you use this "fall-through" feature -- except for
code like the example above, where it's fairly obvious from the
long string of "case n:" without any intervening code.
switch (x) {
case 1:
// some stuff that has to happen in case 1
/* *** FALL THROUGH *** */
case 2:
// some stuff that has to happen either for 1 or 2
break;
}
In a case such as the VB example you gave above, a chained if-else
might in fact be clearer and less verbose:
if (1 <= x && x <= 10) {
// do some stuff
} else if (x == 11 || x == 14 || x == 16) {
// do some other stuff
} else {
// complain
}
--
Chris Jeris
Apply (1 6 2 4)(3 7) to domain to reply.