在javascript中打破标签和没有标签之间有什么区别 [英] what the difference between break with label and without label in javascript

查看:98
本文介绍了在javascript中打破标签和没有标签之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

< pre class =snippet-code-js lang-js prettyprint-override> 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.



但是为什么如果我添加标签,结果会变成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只会打破当前循环,在你的情况下是最里面的。所以现在j = 6,条件现在是错误的,并且循环继续增加40个。



当你放一个标签时,中断转到级别标签,因此跳过两个for循环。


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

解决方案

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.

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

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