JavaScript while 循环


目录

    显示目录


循环可以执行一段代码 只要指定的条件为真。


while 循环

只要指定条件为真,while 循环就会循环执行代码块。

句法

while (condition) {
      // code block to be executed
 }

例子

在下面的示例中,循环中的代码将一遍又一遍地运行,只要 变量 (i) 小于 10:

例子

while (i < 10) {
    text += "The number is " + i;
    i++;
}
 

自己尝试一下 →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript While Loop</h2>

<p id="demo"></p>

<script>
let text = "";
let i = 0;
while (i < 10) {
  text += "<br>The number is " + i;
  i++;
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

如果您忘记增加条件中使用的变量,则循环将永远不会结束。 这将使您的浏览器崩溃。


do while 循环

do while 循环是 while 循环的变体。这个循环将 执行一次代码块,然后检查条件是否为真,然后 只要条件为真,就重复循环。

句法

do {
      // code block to be executed
}
while (condition);

例子

下面的示例使用 do while 循环。循环永远是 即使条件为假,也至少执行一次,因为代码块 在测试条件之前执行:

例子

do {
    text += "The number is " + i;
    i++;
 }
while (i < 10);

自己尝试一下→

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Do While Loop</h2>

<p id="demo"></p>

<script>
let text = ""
let i = 0;

do {
  text += "<br>The number is " + i;
  i++;
}
while (i < 10);  

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

不要忘记增加条件中使用的变量,否则 循环永远不会结束!



比较 forwhile

如果你读过前面关于 for 循环的章节,你会发现 while 循环是 与 for 循环非常相似,只是省略了语句 1 和语句 3。

本示例中的循环使用 for 循环来收集汽车 汽车数组中的名称:

例子

const cars = ["BMW", "Volvo", "Saab", "Ford"];
let i = 0;
let text = "";

for (;cars[i];) {
    text += cars[i];
   
i++;
}

自己尝试一下 →

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
const cars = ["BMW", "Volvo", "Saab", "Ford"];

let i = 0;
let text = "";
for (;cars[i];) {
  text += cars[i] + "<br>";
  i++;
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

此示例中的循环使用 while 循环来收集 cars 数组中的汽车名称:

例子

const cars = ["BMW", "Volvo", "Saab", "Ford"];
let i = 0;
let text = "";
 
 while (cars[i]) {
    text += cars[i];
   
i++;
}

自己尝试一下→

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
const cars = ["BMW", "Volvo", "Saab", "Ford"];

let i = 0;
let text = "";
while (cars[i]) {
  text += cars[i] + "<br>";
  i++;
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>