[英]for in loop weird behavior
I've got some weird behavior with a for-in loop. 我在for-in循环中有一些奇怪的行为。
Code: 码:
var obj = {
q:1,
w:2,
e:4,
r:5
};
function test(data) {
for (key in data) {
//do sth;
}
}
!function() {
for (key in obj) {
console.log(key);
test({a:1,b:2,c:3});
console.log(key);
}
}();
as i expected the output should be sth like this: 正如我期望的那样,输出应该是这样的:
qqwweerr qqwweerr
but i got this: 但是我得到了这个:
qcwcecrc qcwcecrc
i can't find the logic behind this behavior! 我找不到这种行为背后的逻辑! the key variables are scoped lexically ! 关键变量是按词法定义的! what's worng with my code? 我的代码磨损了什么?
You need to declare key
with var
in both functions. 您需要在两个函数中都使用var
声明key
。 Currently, it's an implicit global variable. 当前,它是一个隐式全局变量。
function test(data){
for (var key in data){
//do sth;
}
}
Because it's global, references to key
in both function involve the same variable, so the loop in test()
messes up the loop in the anonymous function. 因为是全局的,所以两个函数中对key
引用都涉及相同的变量,因此test()
的循环将匿名函数中的循环弄乱了。
(You could use let
instead of var
if you wanted to, though in this case it would make no difference.) (如果需要,可以使用let
而不是var
,尽管在这种情况下没有什么区别。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.