break
语法
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)The definition of 'Break statement' in that specification. | Standard | |
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Break statement' in that specification. | Standard | |
ECMAScript Latest Draft (ECMA-262)The definition of 'Break statement' in that specification. | Draft | |
浏览器兼容性
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
Feature | Android | Chrome for Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com

