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>

更新時間: 13-6 月-2020

299 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告