JavaScript 中的 if...else if... 語句是什麼?


if...else if... 語句是 if...else 的高階形式,它允許 JavaScript 根據多個條件制定正確的決策。

語法

if-else-if 語句的語法如下 −

if (expression 1){
   Statement(s) to be executed if expression 1 is true
}
else if (expression2){
   Statement(s) to be executed if expression 2 is true
}
else if (expression3){
   Statement(s) to be executed if expression 3 is true
}
else{
   Statement(s) to be executed if no expression is true
}

示例

您可以嘗試執行以下內容,瞭解如何在 JavaScript if...else if 語句中進行操作 −

線上演示

<html>
   <body>
      <script>
         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>EconomicsBook</b>");
         }
         else{
            document.write("<b>Unknown Book</b>");
         }
      </script>
   </body>
<html>

更新於: 2020 年 6 月 13 日

299 次瀏覽

開啟您的 職業生涯

完成課程後獲得認證

開始
廣告