从JavaScript 1.2开始,您可以使用 switch 语句来处理这种情况,它比重复的 if ... else if 语句更有效。
流程图
以下流程图说明了switch-case语句的工作原理。
switch 语句的目的是给出一个要求值的表达式,并根据表达式的值执行多个不同的语句。解释器会根据表达式的值检查每个 case 条件 ,直到找到匹配项,如果没有匹配项,将使用默认(default)条件。
switch (expression) { case condition 1: statement(s) break; case condition 2: statement(s) break; ... case condition n: statement(s) break; default: statement(s) }
break 语句指示特定案例的结束,如果省略它们,则在以下每种情况下,解释器将继续执行每个语句。
请尝试以下示例来实现switch-case语句。
<html> <body> <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> <p>Set the variable to different value and then try...</p> </body> </html>
运行上面代码输出
Entering switch block Good job Exiting switch block Set the variable to different value and then try...
break语句在switch-case语句中起主要作用,请尝试以下使用switch-case语句而不使用任何break语句的代码。
<html> <body> <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> <p>Set the variable to different value and then try...</p> </body> </html>
运行上面代码输出
Entering switch block Good job Pretty good Passed Not so good Failed Unknown grade Exiting switch block Set the variable to different value and then try...
参考链接
https://www.learnfk.com/javascript/javascript-switch-case.html