break
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
尝试一下
let i = 0;
while (i < 6) {
if (i === 3) {
break;
}
i = i + 1;
}
console.log(i);
// Expected output: 3
语法
描述
示例
中断 while 循环
以下函数有一个 break
语句,当 i
等于 3 时终止 while
循环,然后返回值 3 * x
。
js
function testBreak(x) {
let i = 0;
while (i < 6) {
if (i === 3) {
break;
}
i += 1;
}
return i * x;
}
switch 语句中的 break
以下代码有一个 break
语句,当匹配到一个 case
并执行完相应的代码后,会终止 switch
语句。
js
const food = "寿司";
switch (food) {
case "寿司":
console.log("寿司原产于日本。");
break;
case "披萨":
console.log("披萨原产于意大利。");
break;
default:
console.log("我从未听说过这道菜。");
break;
}
带标签的 break 语句
以下代码展示了如何使用带标签的 break
语句。通过使用 break outerBlock
语句,可以跳出标记为 outerBlock
的嵌套循环或块语句。
js
outerBlock: {
innerBlock: {
console.log("1");
break outerBlock; // 同时跳出 innerBlock 和 outerBlock
console.log(":-("); // 跳过这一行
}
console.log("2"); // 跳过这一行
}
非法 break 语句
一个 break
语句必须嵌套在它引用的任何标签内部。以下代码也使用了带 break
语句的标签,但是会产生语法错误,因为其 break
语句引用了 block2
,但它并未嵌套在 block2
内。
js
block1: {
console.log("1");
break block2; // SyntaxError: label not found
}
block2: {
console.log("2");
}
以下代码示例中,在嵌套在循环或带标签块中的函数内使用 break
语句也会产生语法错误,而 break
语句旨在跳出这些循环或带标签块。
js
function testBreak(x) {
let i = 0;
while (i < 6) {
if (i === 3) {
(() => {
break;
})();
}
i += 1;
}
return i * x;
}
testBreak(1); // SyntaxError: Illegal break statement
js
block1: {
console.log("1");
(() => {
break block1; // SyntaxError: Undefined label 'block1'
})();
}
规范
Specification |
---|
ECMAScript® 2025 Language Specification # sec-break-statement |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
break |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.