JavaScript While 循環

JavaScript While 循環

  • JS Loop For
  • JS Break


JavaScript While 循環


只要條件為 true,循環能夠一直執行代碼塊。

While 循環

while 循環會一直循環代碼塊,只要指定的條件為 true。

語法

<code>while (條件) {
要執行的代碼塊
}
/<code>

實例

在下面的例子中,循環中的代碼將運行,一遍又一遍,只要變量(i)小於 10:

<code>while (i < 10) {
text += "數字是 " + i;
i++;
}
/<code>

如果您忘了對條件中使用的變量進行遞增,那麼循環永不會結束。這會導致瀏覽器崩潰。

Do/While 循環

do/while 循環是 while 循環的變體。在檢查條件是否為真之前,這種循環會執行一次代碼塊,然後只要條件為真就會重複循環。

語法

<code>do {
要執行的代碼塊
}

while (條件);
/<code>

實例

下面的例子使用了 do/while 循環。該循環會執行至少一次,即使條件為 false,因為代碼塊會在條件測試之前執行:

<code>do {
text += "The number is " + i;
i++;
}
while (i < 10);
/<code>

不要忘記對條件中所用變量進行遞增,否則循環永不會結束!

比較 For 與 While

如果您已經閱讀了之前關於循環的章節,您會發現 while 循環與 for 循環相當類似,其中的語句 1 和 語句 2 都可以省略。

本例中的循環使用 for 循環來提取 cars 數組中的汽車品牌:

實例

<code>var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;

var text = "";

for (;cars[i];) {
text += cars[i] + "
";
i++;
}
/<code>

本例中的循環使用 while 循環來提取 cars 數組中的汽車品牌:

實例

<code>var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = "";

while (cars[i]) {
text += cars[i] + "
";
i++;
}
/<code>


分享到:


相關文章: