JavaScript break 语句

JavaScript break 语句是一个重要的关键字,用于改变程序的流程。循环用于执行某个代码块 n 次,直到测试条件为 false。在某些情况下,我们需要在不执行所有语句的情况下终止循环。在这些情况下,我们可以使用 break 和 Continue 语句。

break 语句对于退出任何循环(如 For、While 和 Do While)都非常有用。在执行这些循环时,如果编译器在其中发现 JavaScript break 语句,它将停止运行代码块并立即退出循环。

例如,循环中有五行代码,我们希望在某个条件为 True 时退出循环;否则,它必须执行所有这些代码。在这种情况下,我们可以将 JavaScript Break 语句放在 If 条件内。如果条件为 True,则编译器将执行此语句。这意味着 break 语句将完全将控制器退出循环。否则,它将执行所有行。

注意:break 语句是 Switch Case 中最重要的语句。没有 break,编译器将不会退出 Switch Case。

JavaScript break 语句示例

break 语句的语法如下:

break;

我们将通过两个示例来展示 break 语句在 For 循环和 While 循环中的工作功能。

For 循环中的 JavaScript break 语句

此程序将在 For 循环中使用 break 语句退出循环迭代。

<!DOCTYPE html>
<html>
<head>
    <title> JavaScriptBreak in For Loop </title>
</head>

<body>
    <h1> JavaScriptBreak </h1>
<script>
    var i;
    for (i = 10; i > 0; i--)
    {
        if(i == 6)
        {
            document.write("<br \>Coming Out of <b> For Loop</b> Where i = " + i);
            break;
        }
        
        document.write("<br \ ><b>Numbers </b>= " + i); 
    } 
</script>
</body>
</html>
JavaScript Break Statement

在 For 循环中,我们将 i 的值初始化为 i = 10。然后使用递减运算符将值减 1。如果您在理解 For 循环时遇到困难,请访问我们的 JavaScript For 文章。

JavaScript For 循环中,我们放置了 If 条件来测试 i 是否等于 6。如果条件为 false,它将跳过 break 并将该数字作为输出打印(在我们的例子中是 10、9、8、7)。

如果此条件为 True,则将执行 break。接下来,迭代将在该数字停止,而不会打印其他行。

While 循环中的 JavaScript break 语句

我们将使用 break 语句在 While 循环中退出循环迭代。

<!DOCTYPE html>
<html>
<head>
    <title> For Loop </title>
</head>

<body>
    <h1> Example </h1>
<script>
    var i = 0;
    while (i <= 10)
    {
        document.write("<br \ ><b>The Value of the Variable </b>= " + i);
        i++;
        
        if(i == 4)
        {
            break;
        }
    }
    document.write("<br \>This statement is from Outside While Loop = " + i);
</script>
</body>
</html>
Example

The Value of the Variable = 0
The Value of the Variable = 1
The Value of the Variable = 2
The Value of the Variable = 3
This statement is from Outside While Loop = 4

我们在代码开头将 i 的值初始化为 i = 0。在 While 循环中,我们检查 i 是否小于或等于 10。如果您在理解 While 循环时遇到困难,请访问我们的 JS While 文章。

在 While 循环中,我们放置了 if 条件来测试 i 是否等于 4。如果条件为 false,它将跳过 break 语句并将该数字作为输出打印(在我们的例子中是 0、1、2、3)。

如果此条件为 True,则将执行 Break 语句。接下来,迭代将在该数字停止,而不会打印其他 printf 函数。