“变种"或没有“var"在 JavaScript 的“for-in"中环形? [英] "var" or no "var" in JavaScript's "for-in" loop?

查看:16
本文介绍了“变种"或没有“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 则它是全局的(如果您处于严格模式,using strict,全局变量会抛出错误).这可能会导致如下问题.

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

如果您在 for 循环中写入 var i,警报将显示 2.

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

JavaScript 范围和提升

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

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