console.log() displays the value of a variable before it actually changed
P粉356361722
P粉356361722 2023-08-22 17:35:57
0
2
402
<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>
P粉356361722
P粉356361722

reply all(2)
P粉578680675

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:

console.log(JSON.parse(JSON.stringify(c)))

MDNWARNING:

P粉949848849

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template