Weird console.logbehavior in chrome

2019-05-30 14:27发布

问题:

I haven't been able to reproduce this problem with another script, so please run this script: http://jsfiddle.net/kz4k7/

As you can see at line 154-157:

for (myKey in v){
    console.log("v["+myKey +"] = "+v[myKey]); 
}
console.log(v);

you would expect the first three lines to output the same as the last line. However I get this result in chrome:

If I remove the solveTriangle(v) at line 158, the console.log(v); works perfectly fine. It also works if I print a cloned version of the object v to the console.

Note: This isn't finished at all, I just want to know why chrome does this. I also don't want to explain "why have you done it that way?" and other questions unrelated to this bug.

Edit:

This is also the behavior in Safari.

Firefox + firebug screenshot:

回答1:

console.log shows what the object contains when you open it (by clicking the arrow), not when it was logged. Frankly, your code it pretty verbose and a bit messy with lots of commented-out code, but it seems like you're indeed modifying the object after logging it.

You can confirm this log behaviour with the following simplified test: http://jsfiddle.net/e7Gvn/.

var o = {
    a: 1,
    b: 2
};

console.log( JSON.stringify(o) ); // force string logging, which doesn't change

console.log(o); // open the object and you'll see that `c = 3`...
o.c = 3;        // ... even though it was only set here


回答2:

That's a rather simple problem. Chrome stores references to the object. If you look at the object after your script has finished, you get this observed behaviour, because the object changed and is not the same as when the console.log fired.

If you set a breakpoint at the line containing console.log(v); and inspect the value, the result will be what you expected.