此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。
break
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
In this article
嘗試一下
let i = 0;while (i < 6) { if (i === 3) { break; } i = i + 1;}console.log(i);// Expected output: 3語法
break [label];
說明
中斷陳述break 可加上標籤 (label) 參數,使其跳出被標籤的陳述語句。此中斷陳述break 必須被包含在被標籤的陳述語句中。被標籤的陳述語句可被添加於任一個區塊 (block) 前,而非限定在迴圈陳述。
範例
下面函式包含一個中斷陳述break ,當i 值為 3 時,中斷while 迴圈,並回傳3 * x 。
function testBreak(x) { var i = 0; while (i < 6) { if (i == 3) { break; } i += 1; } return i * x;}The following code usesbreak statements with labeled blocks. Abreak statement must be nested within any label it references. Notice thatinner_block is nested withinouter_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}The following code also usesbreak statements with labeled blocks but generates a Syntax Error because itsbreak statement is withinblock_1 but referencesblock_2. Abreak statement must always be nested within any label it references.
block_1: { console.log('1'); break block_2; // SyntaxError: label not found}block_2: { console.log('2');}規範
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-break-statement> |