javascript infinite loop caused by simple for loop

不打扰是莪最后的温柔 提交于 2021-02-09 07:04:13

问题


I get an infinite loop because of this small bit of code. It becomes fixed if I declared the var i to any value (i.e. var i = 0) before the loop, and I'm not sure why. Could someone who's familiar with javascript's intricacies explain to me what's going on here?

for (num = 1; num <= 2; num++) {
    for (i = 1; i < num; i++) {
      console.log("hi");
    }
}

回答1:


Since i was not declared as a local var, your code is, in-effect altering variables/objects window.i as well as window.num

Adding var keywords should fix the problem:

for (var num = 1; num <= 2; num++) {
    for (var i = 1; i < num; i++) {
      console.log("hi");
    }
}

This doesn't answer the question why the program goes into an infinite loop. But you only know that the hanging code was trying to alter window.i and window.num which might be used elsewhere.

Read more about javascript scoping rules.




回答2:


The code seems to be just fine, see it in action on jsFiddle here.

Another note: Be careful with variables in javascript. You should always use var to declare them; if you forget that they'll end up being globals!




回答3:


It shouldn't be infinite but here is the case that might happened.

You are accessing i without declaring var means you are using it as a global variable not local. Try to analyse your code carefully to find out any global 'i' or 'num' that is messing around your loop.



来源:https://stackoverflow.com/questions/10798993/javascript-infinite-loop-caused-by-simple-for-loop

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