View Single Post
  #4 (permalink)  
Old March 9th, 2015, 10:37 PM
msossoman msossoman is offline
Registered User
Points: 3, Level: 1
Points: 3, Level: 1 Points: 3, Level: 1 Points: 3, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Feb 2015
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default switch with MANY cases

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?
Reply With Quote