JavaScript - continue 语句
JavaScript 中的 continue 语句用于跳过循环的当前迭代并继续进行下一次迭代。它通常与 if 语句结合使用,用于检查条件,并在条件满足时跳过迭代。
JavaScript continue 语句指示解释器立即开始循环的下一次迭代并跳过剩余的代码块。遇到 continue 语句时,程序流程会立即转到循环检查表达式,如果条件仍然为真,则开始下一次迭代,否则退出循环。
语法
JavaScript 中 continue 语句的语法如下:
continue; OR continue label;
我们可以在 for 循环、while 循环、dowhile 循环等循环中使用 continue 语句。
我们将在下一章中学习如何将 continue 语句与标签语句一起使用。
for 循环中的 continue 语句
以下示例将 continue 语句与 for 循环一起使用。在循环中,当 x 的值为 3 时,它将执行 continue 语句以跳过当前迭代并转到下一次迭代。
在输出中,您可以看到循环没有打印 3。
示例
<html>
<head>
<title> JavaScript - Continue statement </title>
</head>
<body>
<p id = "output"> </p>
<script>
let output = document.getElementById("output");
output.innerHTML += "Entering the loop. <br /> ";
for (let x = 1; x < 5; x++) {
if (x == 3) {
continue; // 跳过循环体的剩余部分
}
output.innerHTML += x + "<br />";
}
output.innerHTML += "Exiting the loop!<br /> ";
</script>
</body>
</html>
输出
Entering the loop. 1 2 4 Exiting the loop!
带有 while 循环的 continue 语句
在下面的示例中,我们使用了带有 continue 语句的 while 循环。在 while 循环的每次迭代中,我们将 x 的值加 1。如果 x 的值等于 2 或 3,则跳过当前迭代并进入下一次迭代。
在输出中,您可以看到代码没有打印 2 或 3。
示例
<html>
<head>
<title> JavaScript - Continue statement </title>
</head>
<body>
<p id = "output"> </p>
<script>
let output = document.getElementById("output");
var x = 1;
output.innerHTML += "Entering the loop. <br /> ";
while (x < 5) {
x = x + 1;
if (x == 2 || x == 3) {
continue; // 跳过循环体的其余部分
}
output.innerHTML += x + "<br />";
}
output.innerHTML += "Exiting the loop!<br /> ";
</script>
</body>
</html>
输出
Entering the loop. 4 5 Exiting the loop!
嵌套循环中的 continue 语句
您可以将 continue 语句与嵌套循环一起使用,并跳过父循环或子循环的迭代。
示例
在下面的代码中,父循环遍历了 1 到 5 个元素。在父循环中,我们使用 continue 语句在 x 的值为 2 或 3 时跳过迭代。此外,我们定义了嵌套循环。在嵌套循环中,当 y 的值为 3 时,我们跳过循环迭代。
在输出中,您可以观察到 x 和 y 的值。您不会看到 x 的值是 2 或 3,y 的值是 3。
<html>
<head>
<title> JavaScript - Continue statement </title>
</head>
<body>
<p id = "output"> </p>
<script>
let output = document.getElementById("output");
output.innerHTML += "Entering the loop. <br /> ";
for (let x = 1; x < 5; x++) {
if (x == 2 || x == 3) {
continue; // 跳过循环体的其余部分
}
for (let y = 1; y < 5; y++) {
if (y == 3) {
continue;
}
output.innerHTML += x + " - " + y + "<br />";
}
}
output.innerHTML += "Exiting the loop!<br /> ";
</script>
</body>
</html>
输出
Entering the loop. 1 - 1 1 - 2 1 - 4 4 - 1 4 - 2 4 - 4 Exiting the loop!

