JavaScript - if ... else语句

在编写程序时,可能存在需要从给定路径集中采用一个程序的情况。在这种情况下,您需要使用条件语句,使您的程序能够做出正确的决策并执行正确的操作。

JavaScript支持条件语句,用于根据不同的条件执行不同的操作。在这里,我们将解释 if..else 语句。

if-else的流程图

以下流程图显示if-else语句的工作原理。

决策制定

JavaScript支持以下形式的 if..else 语句 :

  • if statement

  • if ... else statement

  • if ... else if ... statement。

if statement

if 语句是基本控件允许JavaScript有条件地做出决策和执行语句的语句。

语法

基本if语句的语法如下 :

if(expression){
    如果表达式为真,则执行的语句
}


这里评估一个JavaScript表达式。如果结果值为true,则执行给定的语句。如果表达式为false,则不会执行任何语句。大多数情况下,您将在做决定时使用比较运算符。

示例

尝试以下示例以了解如何声明有效。

在线演示

<html>
   <body>     
      <script type = "text/javascript">
         <!--
            var age = 20;
         
            if( age > 18 ) {
               document.write("<b>Qualifies for driving</b>");
            }
         //-->
      </script>      
      <p>Set the variable to different value and then try...</p>
   </body>
</html>


输出

  Qualifies for drivingSet the variable to different value and then try...


if ... else statement

'if ... else'语句是控制语句的下一种形式,它允许JavaScript以更加可控的方式执行语句。

语法

if(expression){
    如果表达式为真,则执行的语句
} else {
    表达式为false时要执行的语句
}


此处评估JavaScript表达式。如果结果值为true,则执行"if"块中的给定语句。如果表达式为false,则执行else块中的给定语句。

示例

尝试以下代码以了解如何在JavaScript中实现if-else语句。

在线演示

<html>
   <body>   
      <script type = "text/javascript">
         <!--
            var age = 15;
         
            if( age > 18 ) {
               document.write("<b>Qualifies for driving</b>");
            } else {
               document.write("<b>Does not qualify for driving</b>");
            }
         //-->
      </script>     
      <p>Set the variable to different value and then try...</p>
   </body>
</html>


输出

 Does not qualify for drivingSet the variable to different value and then try...


if ... else if ... statement

if ... else if ... 语句是 if ... else 的高级形式,允许JavaScript做出正确的决定几个条件。

语法

if-else-if语句的语法如下 :

if(expression 1){
    如果表达式1为真,则执行语句
}else if(expression 2){
    如果表达式2为真,则执行的语句
}else if(expression 3){
    如果表达式3为真,则执行的语句
} else {
如果没有表达式为true,则执行语句
}


此代码没有什么特别之处。它只是一系列 if 语句,其中每个 if 是前一个语句的 else 子句的一部分。语句是根据真实条件执行的,如果没有条件为真,则执行 else 块。

示例

尝试使用以下代码来学习如何在JavaScript中实现if-else-if语句。

在线演示

<html>
   <body>   
      <script type = "text/javascript">
         <!--
            var book = "maths";
            if( book == "history" ) {
               document.write("<b>History Book</b>");
            } else if( book == "maths" ) {
               document.write("<b>Maths Book</b>");
            } else if( book == "economics" ) {
               document.write("<b>Economics Book</b>");
            } else {
               document.write("<b>Unknown Book</b>");
            }
         //-->
      </script>      
      <p>Set the variable to different value and then try...</p>
   </body>
<html>


输出

 Maths BookSet the variable to different value and then try...