user2470628 user2470628 - 1 year ago 98
Javascript Question

for in loop weird behavior

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


var obj = {

function test(data) {
for (key in data) {
//do sth;

function() {
for (key in obj) {

as i expected the output should be sth like this:

q q w w e e r r

but i got this:

q c w c e c r c

i can't find the logic behind this behavior!
the key variables are scoped lexically !
what's worng with my code?

Answer Source

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