JavaScript while 循環(huán)
只要指定條件為 true,循環(huán)就可以一直執(zhí)行代碼塊。
while 循環(huán)會在指定條件為真時(shí)循環(huán)執(zhí)行代碼塊。
語法
while (條件){ 需要執(zhí)行的代碼 }
條件可以是返回 true 或 false 的任何條件語句。
JavaScript while 循環(huán)
實(shí)例
本例中的循環(huán)將繼續(xù)運(yùn)行,只要變量 i 小于 5:
<script> var x = '', i = 0; while (i<5){ x=x + "The number is " + i + "<br />"; i++; } document.write(x); </script>
var x = 1;
(x <= ) {
document.write(x + "<br>");
x = +1;
}
JavaScript while 循環(huán)
如果您忘記增加條件中所用變量的值,該循環(huán)永遠(yuǎn)不會結(jié)束。這可能導(dǎo)致瀏覽器崩潰。
確保 while 循環(huán)中的條件最終變?yōu)?nbsp;false。