What is the use case for “break Identifier” in JavaScript?

后端 未结 2 641
渐次进展
渐次进展 2021-01-18 18:21

the spec goes

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

then it goes

2条回答
  •  [愿得一人]
    2021-01-18 18:59

    If you look on MDN, there's examples

    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
    }
    

    as you can see, you can break with an identifier that selects a label higher up in the chain than just the first immediate parent statement.

    The default action without an identifier would be

    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
    }
    

    The break has to be inside the label, you can't break labels based on indentifiers that the break is outside of.

提交回复
热议问题