I wrote the following code for the book "Beginning JavaScript" Chapter 3, Example 3:
Code:
<script>
var secretNumber = parseInt (prompt ("Pick a number between 1 and 5.", ""), 10);
switch (secretNumber) {
case 1:
case 2:
document.write ("Too low.");
break;
case 3:
document.write ("You guessed the number!");
break;
case 4:
case 5:
document.write ("Too high.");
break;
default:
document.write ("That's not a number between 1 and 5.");
break;
};
</script>
and it works just fine. But what if I want to have the user pick a number and not set any parameters (or my parameters were say 1 to 1 million)? I know the most efficient thing to do would be to write an if/else if/if statement like so:
Code:
if (secretNumber == 42) {
document.write ("You guessed the number!");
} else if (secretNumber < 42) {
document.write ("Too low.");
} else {
document.write ("Too high.");
};
Here's my question - is there a way to write a switch statement with more than just a few case statements and not have to type every single case statement? If I asked the user to try and guess the secretNumber 42 and they could choose any number between 1 and 100, instead of typing my code:
Code:
case 1:
case 2:
case 3:
// and so on all the way to
case 41:
break;
case 42:
break;
case 43:
case 44:
// and so on all the way to
case 100:
break;
is there a way I could do something like:
Code:
case (secretNumber < 42):
document.write ("Too low.");
break;
case 42:
document.write ("You guessed the number!");
break;
case (secretNumber > 42 && secretNumber <= 100):
document.write ("Too high.");
break;
default:
document.write ("That's not a number between 1 and 5.");
break;
If there is a way to do a switch statement like this, and if so, what is the syntax for the case statements?