简单的for循环引起的javascript无限循环 [英] javascript infinite loop caused by simple for loop

查看:57
本文介绍了简单的for循环引起的javascript无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于这小段代码,我陷入了无限循环.如果我在循环之前将var i声明为任何值(即var i = 0),它将变得固定,并且我不确定为什么.熟悉JavaScript的复杂性的人可以向我解释一下这里发生了什么吗?

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

推荐答案

由于未将 i 声明为本地 var ,因此您的代码是有效的更改变量/objects window.i 以及 window.num

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

添加 var 关键字应该可以解决此问题:

Adding var keywords should fix the problem:

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

这没有回答为什么程序进入无限循环的问题.但是您只知道挂起的代码正在尝试更改可能在其他地方使用的 window.i window.num .

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.

详细了解 javascript范围规则.

这篇关于简单的for循环引起的javascript无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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