console.log() displays the changed value before the variable value actually changes
P粉427877676
2023-08-27 22:37:24
<p>I understand this code. We copy A and call it C. When A changes, C remains unchanged</p>
<pre class="brush:php;toolbar:false;">var A = 1;
var C = A;
console.log(C); // 1
A;
console.log(C); // 1</pre>
<p>But when A is an array, the situation is different. Not only does C change, but it changes before we touch A</p>
<pre class="brush:php;toolbar:false;">var A = [2, 1];
var C = A;
console.log(C); // [1, 2]
A.sort();
console.log(C); // [1, 2]</pre>
<p>Can someone explain what is happening in the second example? </p>
console.log()
will pass a reference to the object, so the value in the console will change as the object changes. To avoid this you can:MDN WARNING:
Pointy's answer provides good information, but it is not the correct answer to this question.
The behavior described by the OP was part of a bug first reported in March 2010 and patched for Webkit in August 2012, but has not yet been integrated into Google Chrome as of this writing. Behavior depends on whether the console debug window is
open
or closed when passing an object literal to console.log() .Excerpt from the original bug report (https://bugs.webkit.org/show_bug .cgi?id=35801):
Chromium Developer Response:
A lot of complaints ensued, which eventually led to a bug fix.
Changelog description for patch implemented in August 2012 (http://trac.webkit.org/changeset/ 125174):