javascript中带标签和不带标签有什么区别 [英] what the difference between break with label and without label in javascript

查看:33
本文介绍了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.

这篇关于javascript中带标签和不带标签有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆