2015-12-18 6 views
5

スペックgoesJavaScriptの「ブレーク識別子」の使用例は何ですか?

BreakStatement : 
    break ; 
    break [no LineTerminator here] Identifier ; 

それはプログラムが識別子を囲んでのラベルセットに表示されていないオプションの識別子、(とbreak文が含まれていますが、

を行きます関数境界を超えていない)ステートメント。

次のように...識別子と

A BreakStatementが評価されています。これは、血まみれの地球上の

Return (break, empty, Identifier). 

何を意味するのでしょうか?これは、文としてどこにでも置くことができ

// ... 
mylabel: 
// ... 

+0

関連:http://stackoverflow.com/questions/17752565/breaking-out-of-an-outer-loop-from-an-inner-loop-in-javascript – Barmar

答えて

4

ラベルは、このようなものです。

複数のネストされたループを持つ場合は、break/continueには便利です。

その使用の例:

var i, j; 

loop1: 
for (i = 0; i < 3; i++) {  //The first for statement is labeled "loop1" 
    loop2: 
    for (j = 0; j < 3; j++) { //The second for statement is labeled "loop2" 
     if (i === 1 && j === 1) { 
     continue loop1; 
     } 
     console.log("i = " + i + ", j = " + j); 
    } 
} 

// Output is: 
// "i = 0, j = 0" 
// "i = 0, j = 1" 
// "i = 0, j = 2" 
// "i = 1, j = 0" 
// "i = 2, j = 0" 
// "i = 2, j = 1" 
// "i = 2, j = 2" 
// Notice how it skips both "i = 1, j = 1" and "i = 1, j = 2" 

Source

2

あなたはMDNに見れば、例

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ことができますがあります。

識別子なしのデフォルトのアクションは、ブレークが外のあることindentifiersに基づいてラベルを壊すことができない、

outer_block: { 
    inner_block: { 
     console.log('1'); 
     break; // breaks out of the inner_block only 
     console.log(':-('); // skipped 
    } 
    console.log('2'); // still executed, does not break 
} 

ブレークはラベルの内側になければならないだろう。

関連する問題