javascript中带标签和不带标签有什么区别

2022-01-25 00:00:00 break label javascript

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)

在上面的代码中,我希望结果是 55,但为什么结果是 95.

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

但是为什么如果我添加标签,结果会变成 55?

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);

推荐答案

当不带标签使用时,break 只中断当前循环,在你的情况下是最里面的 for.所以现在 j = 6,条件现在是错误的,循环继续增加 40 次.

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.

当你放一个标签时,break 转到标签的级别",这样两个 for 循环就被跳过了.

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

相关文章