Home  >  Q&A  >  body text

console.log() displays the value of a variable before it actually changed

<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粉356361722P粉356361722424 days ago381

reply all(2)I'll reply

  • P粉578680675

    P粉5786806752023-08-23 15:48:53

    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:

    reply
    0
  • P粉949848849

    P粉9498488492023-08-23 11:15:47

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

    reply
    0
  • Cancelreply