DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> JavaScript綜合知識 >> JavaScript的while循環的使用
JavaScript的while循環的使用
編輯:JavaScript綜合知識     

   這篇文章主要介紹了詳解JavaScript的while循環的使用,是JS入門學習中的基礎知識,需要的朋友可以參考下

  在寫一個程序時,可能有一種情況,當你需要一遍又一遍的執行一些操作。在這樣的情況下,則需要寫循環語句,以減少代碼的數量。

  JavaScript支持所有必要的循環,以幫助您在所有編程的步驟。

  while 循環

  在JavaScript中最基本的循環是while循環,這將在本教程中學習討論。

  語法

  ?

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

  while循環的目的是為了反復執行語句或代碼塊(只要表達式為true)。一旦表達式為假,則循環將被退出。

  例子:

  下面的例子說明了一個基本的while循環:

  ?

1 2 3 4 5 6 7 8 9 10 11 <script type="text/javascript"> <!-- var count = 0; document.write("Starting Loop" + "<br />"); while (count < 10){ document.write("Current Count : " + count + "<br />"); count++; } document.write("Loop stopped!"); //--> </script>

  這將產生以下結果:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 Starting Loop Current Count : 0 Current Count : 1 Current Count : 2 Current Count : 3 Current Count : 4 Current Count : 5 Current Count : 6 Current Count : 7 Current Count : 8 Current Count : 9 Loop stopped!

  do...while 循環:

  do...while loop 類似於while循環,不同之處在於條件檢查發生在循環的末端。這意味著,在循環將總是至少執行一次,即使條件為假。

  語法

  ?

1 2 3 do{ Statement(s) to be executed; } while (expression);

  注意在do... while循環的末尾使用分號。

  例子:

  如在上面的例子中編寫一個使用do... while循環程序。

  ?

1 2 3 4 5 6 7 8 9 10 11 <script type="text/javascript"> <!-- var count = 0; document.write("Starting Loop" + "<br />"); do{ document.write("Current Count : " + count + "<br />"); count++; }while (count < 0); document.write("Loop stopped!"); //--> </script>

  這將產生以下結果:

  ?

1 2 3 Starting Loop Current Count : 0 Loop stopped!
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved