我应该在for in构造中使用var吗? [英] Should I use var in the for in construct?

查看:170
本文介绍了我应该在for in构造中使用var吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一段JavaScript逻辑中使用for循环。
我应该使用var关键字吗?

I make use of a for in loop in a piece of JavaScript logic. Should I use the var keyword or not?

当我根据W3School的例子运行for-in循环时,没有var,那么作为副作用,它被定义为全局范围(窗口)上的属性:

When I run a for-in loop as per W3School's example, without the var then, as a side effect, it gets defined as a property on the global scope (window):

(function () {

  var object = {
      a: 1,
      b: 2
  }
  for (varName in object) {
      alert(varName + " is" + object[varName])
  }

})();

alert(window.varName) //Returns "b" !
//This returns undefined when the for-in is rewritten as for (var varName in object).

编辑:这里是上述代码的小提示,供您欣赏: http://jsfiddle.net/94uEh/

edit: here is a fiddle of the above code for your enjoyment: http://jsfiddle.net/94uEh/

哪个是正确的,首选形成? - 请注意,我希望支持IE 8(EcmaScript< 5)

Which is the correct, preferred form? - Note that I wish to support IE 8 (EcmaScript < 5)

推荐答案

您应该始终使用 var ,如果你想让这个值是本地的。

You should always use var, if you want the value to be local.

使用关键字 object 对于变量,不建议您在浏览器中遇到未定义的行为。

Using the keyword object for a variable, is not recommended, you might run into undefined behavior across browsers.

此外,您通常应避免应用任何假定为全局范围的本地行为。

Also you should generally avoid applying anything that is suppose to be local to the global scope.

这很糟糕:

for (varName in object) {
    alert(varName + " is" + object[varName])
}

这是正确的:

for (var varName in object) {
    alert(varName + " is" + object[varName])
}

如果需要在全局范围内访问此值,则可能是错误的。在全局范围内使用它也是无用的,因为它只是varName中存在的最后一个值。

If you need to access this value in the global scope, you are probably doing it wrong. Also having this in the global scope is useless, as it will only be the last value, that will exist in the varName.

这篇关于我应该在for in构造中使用var吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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