JavaScript while 循环
while 循环
while 循环会在指定条件为真时循环执行代码块。
语法
while (条件)
{
需要执行的代码
}
实例
本例中的循环将继续运行,只要变量 i 小于 10:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<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 + "该数字为 " + i + "<br>";
i++;
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>注意:如果您忘记增加条件中所用变量的值,该循环永远不会结束。这可能导致浏览器崩溃。
运行程序尝试一下
do/while 循环
do/while 循环是 while 循环的变体。该循环会在检查条件是否为真之前执行一次代码块,然后如果条件为真的话,就会重复这个循环。
语法
do
{
需要执行的代码
}
while (条件);
实例
下面的例子使用 do/while 循环。该循环至少会执行一次,即使条件为 false 它也会执行一次,因为代码块会在条件被测试前执行:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<p>点击下面的按钮,只要 i 小于 5 就一直循环代码块。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x="",i=0;
do{
x=x + "该数字为 " + i + "<br>";
i++;
}
while (i<5)
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>运行程序尝试一下

面对疾风吧
能对比下与其他循环的差别就好了
8年前 添加回复 0