JavaScript continue 语句

x33g5p2x  于2022-04-13 转载在 Java  
字(2.3k)|赞(0)|评价(0)|浏览(187)

在本教程中,您将通过示例了解 continue 语句。
    continue 语句用于跳过循环的当前迭代,程序的控制流转到下一个迭代。
    continue 语句的语法是:

continue [label];

注意: label 是可选的,很少使用。

JavaScript continue 语句的工作原理

JavaScript continue 语句的工作原理

for 循环中的 continue

在 for 循环中,continue 跳过当前迭代,控制流跳转到 update 表达式(如上图工作原理)。

示例 1:打印 i 的值
// program to print the value of i
for (let i = 1; i <= 5; i++) {

    // condition to continue    
    if (i == 3) {
        continue;
    }

    console.log(i);
}

输出

1
2
4
5

在上面的程序中,for 循环用于在每次迭代中打印 i 的值。
    注意循环内的 continue 语句。

if(i == 3) {
    continue;
}

这意味着:

  • 当 i 等于3时,continue 语句跳过第三次迭代。
  • 然后,i 变为4,再次检测 condition 和评估 continue 语句。
  • 因此,在接下来的两次迭代中打印 4 和 5。

注意:continue 语句几乎总是与决策语句一起使用。要了解更多信息,请访问JavaScript if…else 语句。
    要了解有关 for 循环的更多信息,请访问JavaScript for 循环。
    注意:break 语句完全终止循环。但是,continue 语句仅跳过当前迭代。

while 循环中的 continue

在 while 循环中,continue 跳过当前迭代,程序的控制流跳回 while 条件。
    continue 语句的工作方式与 while 和 do…while 循环相同。

示例 2:计算正数
// program to calculate positive numbers only
// if the user enters a negative number, that number is skipped from calculation

// negative number -> loop terminate
// non-numeric character -> skip iteration

let sum = 0;
let number = 0;

while (number >= 0) {

    // add all positive numbers
    sum += number;

    // take input from the user
    number = parseInt(prompt('Enter a number: '));

    // continue condition
    if (isNaN(number)) {
        console.log('You entered a string.');
        number = 0; // the value of number is made 0 again
        continue;
    }

}

// display the sum
console.log(`The sum is ${sum}.`);

输出

Enter a number: 1
Enter a number: 2
Enter a number: hello
You entered a string.
Enter a number: 5
Enter a number: -2
The sum is 8.

在上述程序中,用户输入一个数字。while 循环用于打印用户输入的正数的总和。
    注意 continue 语句的使用。

if (isNaN(number)) {
    continue;
}
  • 当用户输入非数字的数字/字符串时,continue 语句跳过当前迭代。然后程序的控制流进入 while 循环的 condition 判断。
  • 当用户输入小于 0 的数字时,循环终止。

在上面的程序中,isNaN()用于检查用户输入的值是否为数字。
    要了解有关 while 循环的更多信息,请访问JavaScript while 循环。

嵌套循环中的 continue

当 continue 在两个嵌套循环内使用时,continue 跳过内部循环的当前迭代。例如,

// nested for loops

// first loop
for (let i = 1; i <= 3; i++) {

    // second loop
    for (let j = 1; j <= 3; j++) {
        if (j == 2) {
          continue;
        }
        console.log(`i = ${i}, j = ${j}`);
    }
}

输出

i = 1, j = 1
i = 1, j = 3
i = 2, j = 1
i = 2, j = 3
i = 3, j = 1
i = 3, j = 3

在上面的程序中,当 continue 语句执行时,它跳过了内循环中的当前迭代,程序的控制流转移到了内循环的 update 表达式。
    因此,值 j = 2 永远不会显示在输出中。

JavaScript 标记的 continue

使用嵌套循环时,您可以跳过当前迭代,并且可以将程序的控制流传递给 label 语句的 update 表达式。
    但是在 JavaScript 中很少使用标签 continue,因为这会使代码更难阅读和理解。
    如果您想了解有关标记为 continue 语句的更多信息,请访问 labeled continue

上一教程 :JS break                                         下一教程 :JS Switch

参考文档

[1] Parewa Labs Pvt. Ltd. (2022, January 1). Getting Started With JavaScript, from Parewa Labs Pvt. Ltd: https://www.programiz.com/javascript/continue-statement

相关文章