国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

while 循環(huán)

while (條件)
  {
  需要執(zhí)行的代碼;
  }

while

for迴圈在已知迴圈的初始和結(jié)束條件時非常有用。而上述忽略了條件的for迴圈容易讓人看不清楚迴圈的邏輯,此時用while迴圈更佳。

while迴圈只有一個判斷條件,條件滿足,就不斷循環(huán),條件不滿足時則退出迴圈。例如我們要計算100以內(nèi)所有奇數(shù)總和,可以用while迴圈實作:

var x = 0;
var n = 99;
while (n > 0) {
    x = x + n;
    n = n - 2;
}
x; // 2500

在迴圈內(nèi)部變數(shù)n不斷自減,直到變成-1時,不再滿足while條件,循環(huán)退出。

實例

<!DOCTYPE html>
<html>
<body>
<p>點擊下面的按鈕,只要 i 小于 5 就一直循環(huán)代碼塊。</p>
<button onclick="myFunction()">點擊這里</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x="",i=0;
while (i<5)
  {
  x=x + "The number is " + i + "<br>";
  i++;
  }
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>
do ... while

最後一種循環(huán)是do { ... } while()循環(huán),它和while循環(huán)的唯一區(qū)別在於,不是在每次循環(huán)開始的時候判斷條件,而是在每次迴圈完成的時候判斷條件:

var n = 0;
do {
    n = n + 1;
} while (n < 100);
n; // 100

用do { ... } while()迴圈要小心,迴圈體會至少執(zhí)行1次,而for和while迴圈則可能一次都不執(zhí)行。

實例

<!DOCTYPE html>
<html>
<body>
<p>點擊下面的按鈕,只要 i 小于 5 就一直循環(huán)代碼塊。</p>
<button onclick="myFunction()">點擊這里</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x="",i=0;
do
  {
  x=x + "The number is " + i + "<br>";
  i++;
  }
while (i<5)  
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>


#
繼續(xù)學(xué)習(xí)
||
<html> <head> <script> 'use strict'; var arr = ['Bart', 'Lisa', 'Adam']; var i=0; for( i=0;i<arr.length;i++){ alert("hello,"+arr[i]) } while(i<arr.length){ alert("hello,"+arr[i]); i++; } do{ alert("hello,"+arr[i]) i++ }while(i<arr.length) </script> </head> <body> </body> </html>