這次我們來學習JS中的循環語句:while和do~while,這兩種語句有什麼區別呢?
while循環:進入循環之前檢測條件,如不符合,將一次都不執行;
do~while循環:在每次循環結束時在檢測條件,無論如何,至少檢測一次。
while循環:
語法
while (條件)
{
需要執行的代碼
}
案例:
<script>
var i = 0;
while(i<5){
document.write("the number is "+ i + "</br>");
i++;
}
</script>
先定義i的值爲0,進入循環體中,當0小於5時,輸出當前數字爲0,然後i++,也就是i=i+1;現在i變成了1,再次進入循環,1小於5,輸出數字爲1,i繼續加1,直到i的值小於5,停止循環,頁面上最終會出現
the number is 0
the number is 1
the number is 2
the number is 3
the number is 4
提示:如果您忘記增加條件中所用變量的值,該循環永遠不會結束。該可能導致瀏覽器崩潰。
do~while循環:
語法
do
{
需要執行的代碼
}
while (條件);
案例:
<script>
var i = 0;
do{
document.write("the number is " + i + "</br>");
i++;
}
while(i<4);
</script>
和上面的一樣,我們先給i賦值爲9,進入循環體,進行第一次循環,輸出i的值爲0,i++,然後判斷條件i是否小於4,是的話繼續進行循環,也就是說,無論如何都會先進行一次循環,然後再判斷條件。頁面效果如下:
the number is 0
the number is 1
the number is 2
the number is 3