JavaScript while 循環(huán)
while 循環(huán)是 JavaScript 中最簡單的循環(huán),其語法為:
while (expr){
? ?statement
}
該語法表示,只要 expr 表達(dá)式為 TRUE,那么就一直執(zhí)行 statement 直到 expr 為 FALSE為 止,statement 表示要執(zhí)行的動作或邏輯。
下面的例子利用 while 循環(huán)輸出1到10:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> <script type="text/javascript"> var i = 1; while (i <= 10) { document.write(i + "<br />"); i++; } </script> </head> <body> </body> </html>
運行結(jié)果:
1
2
3
4
5
6
7
8
9
10
do while循環(huán)
do while 循環(huán)和 while 循環(huán)非常相似,其區(qū)別只是在于 do while 保證必須執(zhí)行一次,而 while 在表達(dá)式不成立時則可能不做任何操作。
do while 循環(huán)語法:
do {
? statement
}while (expr)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> <script type="text/javascript"> var i = 1; do { document.write(i + "<br />"); i++; } while (i <= 10); </script> </head> <body> </body> </html>
比較 for 和 while
如果您已經(jīng)閱讀了前面那一章關(guān)于 for 循環(huán)的內(nèi)容,您會發(fā)現(xiàn) while 循環(huán)與 for 循環(huán)很像。
使用?for 循環(huán)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <script> cars=["BMW","Volvo","Saab","Ford"]; var i=0; for (;cars[i];){ document.write(cars[i] + "<br>"); i++; } </script> </body> </html>
使用?while 循環(huán)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <script> cars=["BMW","Volvo","Saab","Ford"]; var i=0; while (cars[i]){ document.write(cars[i] + "<br>"); i++; } </script> </body> </html>