what the difference between break with label and without label in javascript

强颜欢笑 提交于 2019-11-29 07:11:52

问题


var num = 0;
for(var i = 0; i < 10; i++){
  for(var j = 0; j < 10 ; j++){
    if(i == 5 && j == 5){
      break;
    }
    num++;
  }
}

console.log(num)

In the above code, I expect the result to be 55 but why the result is 95.

But why if I added the label, the result become 55?

var num = 0;
outermost:
for(var i = 0; i < 10; i++){
  for(var j = 0; j < 10 ; j++){
    if(i == 5 && j == 5){
      break outermost;
    }
    num++;
  }
}

console.log(num);

回答1:


when used without label, break only break the current loop, in your case the innermost for. So now j = 6, the condition is now wrong, and the loops continues for 40 more incrementation.

When you put a label, break go to the "level" of the label, so the two for loops are skipped.




回答2:


Using break without a label breaks the innermost loop which is currently executing.

Using break with a label foo breaks the statement labeled foo.

MDN break docs:

The break statement includes an optional label that allows the program to break out of a labeled statement. The break statement needs to be nested within this labelled statement. The labelled statement can be any block statement; it does not have to be preceded by a loop statement.




回答3:


Without a label, break will break out of the inner loop. With a label you can stop execution of nested loops.

See the examples:

https://developer.mozilla.org/en/JavaScript/Reference/Statements/label




回答4:


the break is given in only inner for loop. so it breaks only inner for loop when i = j = 5. but the outer loop continues to revolve 10 times. so when i=j=5 the loop will revolve only 5 times and in rest of all cases it will revolve 10 times.




回答5:


when you use break without label , it only breaks the inner loop that is (i=5 j=6) ,(i=5 j=7) ,(i=5 j=8) ,(i=5 j=9) only and loop again starts with (i=6 j=0) to (i=9 j=9) and also count (num ++) startsthats why it show result as 95.

bt when you use break with label i.e. break outermost , it breaks out from the loop label as outermost (i.e the outer loop), thats why6 it gives output as 55




回答6:


The first one is only breaking your "j" loop. After it breaks it, it returns to your "i" loop, and increments "i" to 6. Once "i" is 6, it returns to the "j" loop and the if condition is no longer met. So it continues to add up "num".



来源:https://stackoverflow.com/questions/5118965/what-the-difference-between-break-with-label-and-without-label-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!