這篇文章主要介紹了詳解JavaScript的while循環的使用,是JS入門學習中的基礎知識,需要的朋友可以參考下
在寫一個程序時,可能有一種情況,當你需要一遍又一遍的執行一些操作。在這樣的情況下,則需要寫循環語句,以減少代碼的數量。
JavaScript支持所有必要的循環,以幫助您在所有編程的步驟。
while 循環
在JavaScript中最基本的循環是while循環,這將在本教程中學習討論。
語法
- while (expression){
- Statement(s) to be executed if expression is true
- }
while循環的目的是為了反復執行語句或代碼塊(只要表達式為true)。一旦表達式為假,則循環將被退出。
例子:
下面的例子說明了一個基本的while循環:
- <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>
這將產生以下結果:
- 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循環,不同之處在于條件檢查發生在循環的末端。這意味著,在循環將總是至少執行一次,即使條件為假。
語法
- do{
- Statement(s) to be executed;
- } while (expression);
注意在do... while循環的末尾使用分號。
例子:
如在上面的例子中編寫一個使用do... while循環程序。
- <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>
這將產生以下結果:
- Starting Loop
- Current Count : 0
- Loop stopped!
新聞熱點
疑難解答
圖片精選