前端笔记
长乐王

JavaScript循环语句:While循环

While 循环
只要指定条件为 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,循环将继续。
提示:如果您忘记增加条件中所用变量的值,该循环永远不会结束。该可能导致浏览器崩溃。

do/while 循环
do/while 循环是 while 循环的变体。
该循环会执行一次代码块,然后再检查条件是否为真,如果条件为真的话,就会重复这个循环。
使用 do/while 循环,循环至少会执行一次,即使条件是 false,代码块会在条件被测试前执行:
<!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>
提示:别忘记增加条件中所用变量的值,否则循环永远不会结束!

比较 for 和 while
如果您已经阅读了前面那一章关于 for 循环的内容,您会发现 while 循环与 for 循环很像。
for 语句实例
本例中的循环使用 for 循环来显示 cars 数组中的所有值:
<!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 语句实例
本例中的循环使用使用 while 循环来显示 cars 数组中的所有值:
<!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>
本文番号: 前端笔记 - JavaScript - JavaScript循环语句:While循环

评论