只要指定条件为 true,循环就可以一直执行代码。
<!DOCTYPE html> <html> <body> <p>点击下面的按钮,只要 i 小于 5 就一直循环代码块。</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>注释:While 循环会在指定条件为真时循环执行代码块。本例中只要变量 i 小于 5,循环将继续。
<!DOCTYPE html> <html> <body> <p>点击下面的按钮,只要 i 小于 5 就一直循环代码块。</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>提示:别忘记增加条件中所用变量的值,否则循环永远不会结束!
<!DOCTYPE html> <html> <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> <body> <script> cars=["BMW","Volvo","Saab","Ford"]; var i=0; while (cars[i]) { document.write(cars[i] + "<br>"); i++; } </script> </body> </html>
评论