Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

JavaScript continue

JavaScript continue可以完全控制处理JavaScript中的循环语句。有时,当我们需要跳过循环的某些代码并移至下一个迭代时,就会发生这种情况。可以使用JavaScript的 continue 语句来实现。
JavaScript 用于跳过循环的迭代。与 break 语句不同, continue 语句中断当前迭代并继续执行 循环。可以在 for循环,while循环 do-while循环中使用。在 while循环中使用它时,它会跳回到条件。如果在 for 循环中使用它,则流程将移至更新表达式。
当我们应用 continue 语句时,程序的流程将立即移至条件表达式,如果条件为真,则将开始下一次迭代;否则,控件将退出循环。

语法

continue;
OR
continue[label]; // Using the label reference
它可以与或不与label参数一起使用。 label是语句的标识符名称。它是可选的。
使用一些示例让我们理解 continue 语句。

Example1

在此示例中,我们在 for 循环中使用 continue 语句。在这里,循环的迭代从1开始,到7结束。有一个条件语句检查迭代何时到达4。当迭代达到4时,由于 continue而跳过了迭代。语句并移至下一个迭代。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1> Example of the continue statement in JavaScript</h1>
<h3> Here, you can see that "a == 4" is skipped. </h3>
<p id = "para">

</p>
<script>
var res = "";
var a;
for (a = 1; a <=7; a++) {
  if (a == 4) {
    continue;
  }
  res += "The value of a is : " + a + "<br>";
}
document.getElementById("para").innerHTML = res;
</script>
</body>
</html>
输出
执行上述代码后,输出将为-
 JavaScript Continue语句

Example2

在此示例中,我们在 while 循环中使用continue语句。在这里,我们定义了一个数组 "rainbow" 。循环的迭代从0开始,并在数组的长度处结束。有一个使用OR(||)运算符的条件语句,该条件语句检查迭代何时达到值'Magenta'和'Skyblue'。当达到合适的值时,由于continue语句而跳过了迭代。移至下一个迭代。
<!DOCTYPE html>
<html>
<head>
    <title> JavaScript Continue Statement </title>
</head>
<body>
    <h1> Example of the JavaScript Continue Statement </h1>
<h3> You can see that the arrray values "Magenta" and "Skyblue" are skipped. </h3>
<script>
var rainbow = ["Violet", "Indigo", "Magenta", "Blue", "Skyblue", "Green", "Yellow", "Orange", "Red"];
var i = 0;
var res = "";
while(i < rainbow.length){
  if (rainbow[i] == "Magenta" || rainbow[i] == "Skyblue") {
    i++;
continue;
  }
  res = "";
  res += rainbow[i] + "<br>";
  i++;
  document.write(res);
}
</script>
</body>
</html>
输出
执行上述操作后,输出将为-
JavaScript continue语句

Example3

在此示例中,我们在继续语句中使用了标签。有一个嵌套的for循环,其中外部循环标记为 'label1',而内部循环标记为 'label2'
<!DOCTYPE html>
<html>
<body>
<p> This is an example of the continue statement with the label </p>
<p id="para"></p>
<script>
  var res = "";
  var i, j;
  label1: // This loop is labeled as "label1"
  for (i = 1; i <=5; i++) {
  res += "<br>" + "i = " + i + ", j = ";
    label2: // This loop is labeled as "label2"
    for (j = 1; j <= 4; j++) {
      if (j == 2) {
continue label2;
      }
      document.getElementById("para").innerHTML = res += j + " ";
    }
  }
</script>
</body>
</html>
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4