break 语句中止当前循环,label 语句,并把程序控制流转到紧接着被中止语句后面的语句。
语法
break [label];
-
label -
可选。与语句标签相关联的标识符。如果 break 语句不在一个循环或
switch语句中,则该项是必须的。
描述
break语句包含一个可选的标签,可允许程序摆脱一个被标记的语句。break语句需要内嵌在引用的标签中。被标记的语句可以是任何 块语句;不一定是循环语句。
示例
下面的函数里有个 break 语句,当 i 为 3 时,会中止 while 循环,然后返回 3 * x 的值。
function testBreak(x) {
var i = 0;
while (i < 6) {
if (i == 3) {
break;
}
i += 1;
}
return i * x;
}
下面的代码中一起使用 break 语句和被标记的块语句。一个 break 语句必须内嵌在它引用的标记中。注意,inner_block 内嵌在 outer_block 中。
outer_block:{
inner_block:{
console.log ('1');
break outer_block; // breaks out of both inner_block and outer_block
console.log (':-('); // skipped
}
console.log ('2'); // skipped
}
下面的代码同样使用了 break 语句和被标记的块语句,但是产生了一个语法错误,因为它的 break 语句在 block_1 中,但是引用了 block_2。break 语句必须内嵌在它引用的标签中。
block_1:{
console.log ('1');
break block_2; // SyntaxError: label not found
}
block_2:{
console.log ('2');
}
规范
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 1st Edition (ECMA-262) | Standard | Initial definition. Unlabeled version. |
| ECMAScript 3rd Edition (ECMA-262) | Standard | Labeled version added. |
| ECMAScript 5.1 (ECMA-262) Break statement |
Standard | |
| ECMAScript 2015 (6th Edition, ECMA-262) Break statement |
Standard | |
| ECMAScript Latest Draft (ECMA-262) Break statement |
Draft |
浏览器兼容
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.
Update compatibility data on GitHub
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
break |
Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 3 | Opera Full support Yes | Safari Full support Yes | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
Legend
- Full support
- Full support