在寫一個程序時,可能有一種情況,當你需要一遍又一遍的執行一些操作。在這樣的情況下,則需要寫循環語句,以減少代碼的數量。
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 LoopCurrent Count : 0Current Count : 1Current Count : 2Current Count : 3Current Count : 4Current Count : 5Current Count : 6Current Count : 7Current Count : 8Current Count : 9Loop 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 LoopCurrent Count : 0Loop stopped!
新聞熱點
疑難解答