简体   繁体   中英

for in loop weird behavior

I've got some weird behavior with a for-in loop.

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

but i got this:

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. 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.

(You could use let instead of var if you wanted to, though in this case it would make no difference.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM