while 循環是JavaScript 中最簡單的循環,其語法為:
while (expr){
statement
}
#此語法表示,只要expr 表達式為TRUE,那麼就一直執行statement 直到expr 為FALSE為止,statement 表示要執行的動作或邏輯。
下面的範例利用while 迴圈輸出1到10:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> var i = 1; while (i <= 10) { document.write(i + "<br />"); i++; } </script> </head> <body> </body> </html>
運行結果:
1
2
3
4
5
6
7
8
9
10
##do while迴圈
do while 迴圈和while 迴圈非常相似,其區別只是在於do while 保證必須執行一次,而while 在表達式不成立時則可能不做任何操作。 do while 迴圈語法:do { statement
}while (expr)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> var i = 1; do { document.write(i + "<br />"); i++; } while (i <= 10); </script> </head> <body> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(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 迴圈
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(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>