Java教程

无涯教程-Javascript - Switch语句

本文主要是介绍无涯教程-Javascript - Switch语句,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

从JavaScript 1.2开始,您可以使用 switch 语句来处理这种情况,它比重复的 if ... else if 语句更有效。

流程图

以下流程图说明了switch-case语句的工作原理。

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 blockGood jobExiting switch blockSet 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 blockGood jobPretty goodPassedNot so goodFailedUnknown gradeExiting switch blockSet the variable to different value and then try...

参考链接

https://www.learnfk.com/javascript/javascript-switch-case.html

这篇关于无涯教程-Javascript - Switch语句的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!