1 Switch statements are useful:
The switch statement is used to perform different actions based on different conditions.
Whenever a variable condition is met, the current case content is executed.
The break keyword is used to jump out of a switch code block. Terminates execution of the switch code block. If the keyword is omitted, the next block of code for the Swith statement is executed.
The default keyword specifies what to do when a match does not exist. The default keyword can appear only once in a switch statement.
2 Switch Typical structure:
Switch (variable) {
Case 1:
if the variable and the value of 1 are the same, execute the code at that point
Break
Case 2:
if the variable and the value of 2 are the same, execute the code at that point
Break
Case 3:
if the variable and the value of 3 are the same, execute the code at that point
Break
Default
If the variable and the above values are not the same, execute the code here
Break
}
Example 1: Lifting 2 chestnuts
1 Separate judging variables
<! DOCTYPE html>varNumber = prompt ("One digit of input 0-5"); Switch(number) { Case"0": alert (number); Break; Case"1": number= 1; Break; Case"2": number= 2; Break; Case"3": number= 3; Break; Case"4": number= 4; Break; Case"5": number= 5; Break; } </script>2 Collective Judgment variables
Switch (number) { case ' 0 ':case ' 1 ':case ' 2 ': alert ("1/2/3"); Break ; default : alert ("4/5"); Break ; }
JS Tutorial Series 10:javascript switch statement