break

break 陳述句會中斷目前的迭代、switchlabel 陳述句,並將程式流程轉到被中斷之陳述句後的陳述句。

語法

break [label];
label
可選的。欲中斷陳述句的標籤 (label) 識別。若不是要中斷迭代或 switch,則需加此參數。

說明

中斷陳述 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 uses break statements with labeled blocks. A break statement must be nested within any label it references. Notice that inner_block is nested within 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
}

The following code also uses break statements with labeled blocks but generates a Syntax Error because its break statement is within block_1 but references block_2. A break 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 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  

瀏覽器相容性

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
breakChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 3Opera Full support YesSafari Full support YesWebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support 1.0nodejs Full support Yes

Legend

Full support  
Full support

參見