如何在 JavaScript 中将标签与 continue 语句一起使用?
本教程将教我们在 JavaScript 中将标签与 continue 语句一起使用。在 ES5 中,我们将 label 与 go-to 语句一起使用以跳过迭代,但在 ES6 版本的 JavaScript 中不支持此功能。因此,我们将使用 continue 语句跳过循环迭代或跳过任何单个迭代。
以下是 label 和 continue 语句的基本定义。
label − 它可以是任何字符串,用于为代码块提供名称或标签。
continue − 它用于跳过循环的一次迭代。它是 ES6 中 go-to 语句的替换版本。
语法
用户可以按照以下语法使用标签。
标签: 语句 // 可以是循环、代码块等。
在单循环中使用带有 continue 语句的标签
在本节中,我们将学习如何在单循环中使用 continue 语句。在单循环中使用 continue 语句时,我们不需要使用标签,但我们将使用它来演示标签和‘continue’如何使用关键字可以一起使用。
语法
用户应遵循以下语法来使用标签并通过 while 循环继续关键字。
loop: while () { if ( condition ) { continue loop; // 要跳过循环的下一次迭代,请使用 continue 关键字,后跟循环的标签。 } }
示例 1
在下面的示例中,我们必须使用单个 while 循环并为其添加标签。我们创建了一个字符串数组。如果用户在数组中找到 “hello” 和 “world!” 字符串,我们将继续该循环迭代并跳转到下一次迭代。要跳过下一次迭代,我们将使用 continue 关键字,后跟循环标签。
<html> <head> <title> Using the label with continue keyword. </title> </head> <body> <h2> Using the label with continue keyword. </h2> <h4> If specific string occurs in the array jump to the next iteration. </h4> <div id="output"> </div> <script> let output = document.getElementById("output"); let array = ["welcome", "to", "the", "hello", "world!", "tutorialsPoint!"]; let n = array.length; let i = -1; loop: while (i < n - 1) { i++; if (array[i] == "hello" || array[i] == "world!") { continue loop; } output.innerHTML += array[i] + " "; } </script> </body> </html>
在上面的输出中,用户可以看到,如果数组中出现“hello”和“world!”字符串,它会跳转到循环迭代,并且不会在输出中打印。
示例 2
您可以尝试使用 continue 语句运行带有标签的以下代码。
<html> <body> <script> document.write("Entering the loop!<br /> "); outerloop: // This is the label name for (var i = 0; i < 3; i++) { document.write("Outerloop: " + i + "<br />"); for (var j = 0; j < 5; j++) { if (j == 3) { continue outerloop; } document.write("Innerloop: " + j + "<br />"); } } document.write("Exiting the loop!<br /> "); </script> </body> </html>
带有嵌套 for 循环的标签和 continue 语句
在上面的部分中,我们学习了如何使用带有 continue 关键字的标签。在本节中,我们将学习从子循环跳过父循环或祖父母循环的下一次迭代。
我们只需要更改并将父循环的标签附加在 continue 关键字之后。
语法
以下是使用带有嵌套循环的 continue 语句的语法。
parentLoop: for () { childLoop: for () { if (condition) { continue parentLoop; // 跳转到父循环的下一次迭代 } } }
示例 3
在此示例中,我们使用了两个嵌套 for 循环。我们有两个相同的字符串,并使用嵌套 for 循环匹配两个字符串的每个字符。如果两个字符串中的任何字符都匹配,我们将使用 continue 关键字后跟父循环的标签从子循环跳转到父循环的下一次迭代。
<html> <head> <title> Using the label with continue keyword. </title> </head> <body> <h2> Using the label with continue keyword. </h2> <p> We will jump over the parent loop iteration when string character will match. </p> <div id="output"> </div> <script> let output = document.getElementById("output"); let str1 = "abcd"; let str2 = "abcd"; parentLoop: for (let i = 0; i < str1.length; i++) { childLoop: for (let j = 0; j < str2.length; j++) { if (str2[j] == str1[i]) { continue parentLoop; } else { output.innerHTML += " str1[ " + i + " ] = " + str1[i] + " str2[ " + j + " ] = " + str2[j] + "<br/>"; } } } </script> </body> </html>
用户可以看到,当两个字符串中的任何一个字符匹配时,我们就会跳转到父循环的下一次迭代,这就是上述输出在屏幕上呈现的方式。
结论
用户已经学会了将标签与‘continue’语句一起使用。与 break 语句一样,我们不能将 continue 用于 switch-case 或代码块内。