This article mainly introduces the use of switch statements in JavaScript, is the basic knowledge of JS learning, the need for friends can refer to the
You can use multiple if ... else if statements, such as the previous section, to perform multiple branches. However, this is not always the best solution, especially when all branches depend on the value of a single variable.
Starting with JavaScript1.2, you can use it to handle exactly this case, using a switch statement, which is more efficient if not repeatedly using the IF ... else if statement.
Grammar
The basic syntax for a switch statement gives a expression to evaluate how several different statements are executed based on the value of the expression. The interpreter checks each of the values of the expression until a match is found. If no match occurs, the default (default) condition is used.
?
1 2 3 4 5 6 7 8 9 10 11 |
switch (expression) {case condition 1:statement (s) break, case condition 2:statement (s) break, .... Case Condition N:st Atement (s) break; Default:statement (s)} |
The interpreter indicated by the break statement is the end of a particular case. If they are omitted, the interpreter will continue to execute each statement in each of the following cases (case).
We will explain the break statement in the loop control chapter.
Example:
The following example illustrates a basic while loop:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20-21 |
<script type= "Text/javascript" > <!--var grade= ' A '; document.write ("Entering switch block<br/>"); Switch (grade) {case ' A ': document.write ("Good job<br/>"), break, Case ' B ': document.write ("Pretty good<br/> ;"); Break Case ' C ': document.write ("passed<br/>"); Break Case ' D ': document.write ("Don't so good<br/>"); Break Case ' F ': document.write ("failed<br/>"); Break Default:document.write ("Unknown grade<br/>")} document.write ("Exiting switch block"); --> </script> |
This will produce the following results:
?
1 2 3 |
Entering switch block good job exiting switch block |
Example:
Consider a situation where you do not use the break statement:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14-15 16 |
<script type= "Text/javascript" > <!--var grade= ' A '; document.write ("Entering switch block<br/>"); Switch (grade) {case ' A ': document.write ("Good job<br/>"), Case ' B ': document.write ("Pretty good<br/>"); CA Se ' C ': document.write ("passed<br/>"); Case ' D ': document.write ("Don't so good<br/>"); Case ' F ': document.write ("failed<br/>"); Default:document.write ("Unknown grade<br/>")} document.write ("Exiting switch block"); --> </script> |
This will produce the following results:
?
|
entering switch block good job pretty good passed good Failed Unknown grade exiting switch blocks |