简体   繁体   中英

strange javascript behaviour when calling function in a loop

I'm running a simple test and i get a strange behaviour, here is the js code:

 var handler = function(index,params){

    params.id = index;

}

function test(){
    var params = {'id':0};
    console.log(params);
    gradualRepetitionCalls(0,10,params);
}



function gradualRepetitionCalls(index, maxIndex,params) 
{
    if (index < maxIndex) 
    {
        handler(index,params);
        index++;

        gradualRepetitionCalls(index,maxIndex,params);
    }
}

test();

The strange thing is that the console.log(params) shows that the id is '9' while i would expect it to be '0'. Is console.log() asynchronous?

Well, your code snippet is overly complex, try this:

var params = {id: 0};
console.log(params);
params.id = 1;

In Firefox it shows:

Object { id=0 }

but when I click on an object to drill down, it show id=1 . In Google Chrome it just shows Object , but id=1 when drilled down.

The reason for this odd behaviour is that console understand that you are logging an object (not just a string) and every time you look at the console or refresh it, it display the current state of that object.

If you find this behaviour error-prone and counter-intuitive, here are some workarounds:

console.log(JSON.stringify(params));
console.log(params.id);

Also note that this is how JavaScript debuggers work, it's not JavaScript's fault per se .

No, console.log is synchronous. But you create only one object and "output" this object to the console - after that, you alter the properties of this object (objects are passed by reference!). The console just shows the recent state of this object, not a snapshot from the point of time when it has been logged.

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