" VAR"或者没有“var”在JavaScript的“for-in”中环? [英] "var" or no "var" in JavaScript's "for-in" loop?

查看:89
本文介绍了" VAR"或者没有“var”在JavaScript的“for-in”中环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中编写 for-in 循环的正确方法是什么?浏览器不会对我在此处显示的两种方法中的任何一种发出投诉。首先,有一种方法,其中显式声明迭代变量 x

What's the correct way to write a for-in loop in JavaScript? The browser doesn't issue a complaint about either of the two approaches I show here. First, there is this approach where the iteration variable x is explicitly declared:

for (var x in set) {
    ...
}

或者这种方法更自然地读取但对我来说似乎不正确:

And alternatively this approach which reads more naturally but doesn't seem correct to me:

for (x in set) {
    ...
}


推荐答案

使用 var ,它会减小变量的范围,否则变量会查找最近的闭包,搜索 var 语句。如果它找不到 var 那么它是全局的(如果你处于严格模式,使用严格的),全局变量抛出错误)。这可能导致如下问题。

Use var, it reduces the scope of the variable otherwise the variable looks up to the nearest closure searching for a var statement. If it cannot find a var then it is global (if you are in a strict mode, using strict, global variables throw an error). This can lead to problems like the following.

function f (){
    for (i=0; i<5; i++);
}
var i = 2;
f ();
alert (i); //i == 5. i should be 2

如果你写 var i 在for循环中,警报显示 2

If you write var i in the for loop the alert shows 2.

JavaScript范围和提升

这篇关于&QUOT; VAR&QUOT;或者没有“var”在JavaScript的“for-in”中环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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