JavaScript中的條件判斷語句使用詳解

來源:互聯網
上載者:User

  這篇文章主要介紹了JavaScript中的條件判斷語句使用詳解,是JS入門學習中的基礎知識,需要的朋友可以參考下

  在寫一個程式,可能有一種情況,當你需要採用一個路徑出給定兩個路徑。所以,需要使用條件陳述式,讓程式來做出正確的決策和執行正確的行動。

  JavaScript支援其用於執行根據不同的條件不同的操作條件陳述式。在這裡,我們將解釋if..else語句。

  JavaScript支援if..else語句的形式如下:

  if 語句

  if...else 語句

  if...else if... 語句.

  if 語句:

  if語句是基本的控制語句,它允許JavaScript來作出決定,有條件地執行語句。

  文法:

  ?

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

  這裡的JavaScript運算式expression求值。如果得到的值是true,給定語句執行。如果運算式為假則聲明將不執行。大部分的時間你會使用比較運算在使用決策時。

  例子:

  ?

1 2 3 4 5 6 7 8 <script type="text/javascript"> <!-- var age = 20; if( age > 18 ){ document.write("<b>Qualifies for driving</b>"); } //--> </script>

  這將產生以下結果:

  ?

1 Qualifies for driving

  if...else 語句:

  在if ... else語句是控制語句的下一個表單,允許JavaScript執行更可控語句。

  文法

  ?

1 2 3 4 5 if (expression){ Statement(s) to be executed if expression is true }else{ Statement(s) to be executed if expression is false }

  這裡JavaScript運算式求值。如果結果值是真實的,給定語句在if塊(S),被執行。如果運算式是假,則定的else語句塊被執行。

  例子:

  ?

1 2 3 4 5 6 7 8 9 10 <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>

  這將產生以下結果:

  ?

1 Does not qualify for driving

  if...else if... 文法:

  在if...else if... .控制語句的一個層面推進的形式,JavaScript做正確的決策出了幾個條件。

  文法

  ?

1 2 3 4 5 6 7 8 9 if (expression 1){ Statement(s) to be executed if expression 1 is true }else if (expression 2){ Statement(s) to be executed if expression 2 is true }else if (expression 3){ Statement(s) to be executed if expression 3 is true }else{ Statement(s) to be executed if no expression is true }

  代碼沒有什麼特別之處。這僅僅是一系列的if語句,其中每個if之前的語句是else子句的一部分。聲明是基於true條件執行的,如果非條件是true,那麼else塊執行。

  例子:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 <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>

  這將產生以下結果:

  ?

 

1 Maths Book

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.