Home >Web Front-end >JS Tutorial >Detailed explanation of switch usage and precautions in JavaScript
Syntax
The basic syntax of the switch statement gives an expression to evaluate and calculate several different statements based on the value of the expression. The interpreter checks each case for the expression's value until it finds a match. If there is no match, the default condition will be used.
switch (expression) { case condition 1: statement(s) break; case condition 2: statement(s) break; ... case condition n: statement(s) break; default: statement(s) }
The break statement instructs the interpreter to end under specific circumstances. If they are omitted, the interpreter will continue to execute each statement in each of the following cases.
We will explain the break statement in the loop control chapter.
Example:
The following example illustrates a basic while loop:
##
<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("Not 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:
Entering switch block Good job Exiting switch blockExample: Consider such a situation, if you do not use the break statement:
<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 />"); case 'C': document.write("Passed<br />"); case 'D': document.write("Not 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 Not so good Failed Unknown grade Exiting switch blockJavascript switch usage precautions
<script> var t_jb51_net = 65; switch (t_jb51_net) { case '65': alert("字符串65。jb51.net"); break; } </script>You will find that no dialog box pops up and alert is not executed. Cause analysis:What needs to be made clear here is that switch uses the congruent sign "===" when making judgments. When comparing congruent signs, the first thing to look at is the data type. It's not the same, but here, t_jb51_net is of type Number, and '65' is String. The following code will pop up the dialog box:
<script> var t_jb51_net = 65; switch (t_jb51_net) { case 65: alert("数字65。jb51.net"); break; } </script>
The above is the detailed content of Detailed explanation of switch usage and precautions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!