console.log() displays the value of a variable before it actually changed
P粉356361722
2023-08-22 17:35:57
<p>I understand this code. Let's make a copy of A and call it C. When A changes, C remains the same. </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 even touch A. </p>
<pre class="brush:php;toolbar:false;">var A = [2, 1];
var C = A;
console.log(C); // [2, 1]
A.sort();
console.log(C); // [1, 2]</pre>
<p>Can anyone explain what is happening in the second example? </p>
console.log()
Receives a reference to the object, so when the object changes, the value in the console will also change. To avoid this, you can use the following methods:MDNWARNING:
Pointy's answer provides good information, but is not the correct answer to the question.
The behavior described by the OP is part of a bug that was first reported in March 2010, had a fix for Webkit in August 2012, but as of this writing has not yet been integrated into Google Chrome. The behavior depends on whether the console debug window is
opened
or closed when the object literal is passed to console.log().Excerpt from the original bug report (https://bugs.webkit.org/show_bug.cgi?id=35801):
Response from Chromium developers:
A lot of complaints ensued, eventually leading to a bug fix.
Changelog description of the patch implemented in August 2012 (http://trac.webkit.org/changeset/125174):