詳解JavaScript的while循環(huán)的使用
在寫一個程序時,可能有一種情況,當你需要一遍又一遍的執(zhí)行一些操作。在這樣的情況下,則需要寫循環(huán)語句,以減少代碼的數(shù)量。
JavaScript支持所有必要的循環(huán),以幫助您在所有編程的步驟。
while 循環(huán)
在JavaScript中最基本的循環(huán)是while循環(huán),這將在本教程中學習討論。
語法
while (expression){
Statement(s) to be executed if expression is true
}
while循環(huán)的目的是為了反復執(zhí)行語句或代碼塊(只要表達式為true)。一旦表達式為假,則循環(huán)將被退出。
例子:
下面的例子說明了一個基本的while循環(huán):
<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 循環(huán):
do...while loop 類似于while循環(huán),不同之處在于條件檢查發(fā)生在循環(huán)的末端。這意味著,在循環(huán)將總是至少執(zhí)行一次,即使條件為假。
語法
do{
Statement(s) to be executed;
} while (expression);
注意在do... while循環(huán)的末尾使用分號。
例子:
如在上面的例子中編寫一個使用do... while循環(huán)程序。
<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!

