JavaScript 中的 continue 语句用于跳过循环的当前迭代并继续下一次迭代。它通常与 if 语句结合使用,以检查条件并在满足条件时跳过迭代。
JavaScript continue 语句告诉解释器立即开始循环的下一次迭代并跳过剩余的代码块。当遇到 continue 语句时,程序流会立即移动到循环检查表达式,如果条件保持为真,则开始下一次迭代,否则控件退出循环。
语法
JavaScript 中 continue 语句的语法如下 -
continue;
OR
continue label;
我们可以在循环中使用 continue 语句,例如 for 循环、while 循环、do...while 循环等。
在接下来的章节中,我们将学习如何将 'continue' 语句与 'label' 语句一起使用。
Continue 语句与 for 循环
下面的示例使用带有 for 循环的 continue 语句。在循环中,当 x 的值为 3 时,会执行 continue 语句跳过当前迭代,进入下一次迭代。
在输出中,您可以看到 loop 没有打印 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; // skip rest of the loop body
}
output.innerHTML += x + "<br />";
}
output.innerHTML += "Exiting the loop!<br /> ";
</script>
</body>
</html>
输出
1
2
4
Exiting the loop!
Continue 语句与 while 循环
在下面的示例中,我们将 while 循环与 continue 语句一起使用。在 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; // skip rest of the loop body
}
output.innerHTML += x + "<br />";
}
output.innerHTML += "Exiting the loop!<br /> ";
</script>
</body>
</html>
输出
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; // skip rest of the loop body
}
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>
输出
1 - 1
1 - 2
1 - 4
4 - 1
4 - 2
4 - 4
Exiting the loop!