console.log() shows the changed value of a variable before the value actually changes

后端 未结 7 1992
无人共我
无人共我 2020-11-22 02:09

This bit of code I understand. We make a copy of A and call it C. When A is changed C stays the same

var A = 1;
var C = A;
console.log(C); // 1
A++;
console.         


        
7条回答
  •  盖世英雄少女心
    2020-11-22 02:43

    Console.log() is passed a reference to the object, so the value in the Console changes as the object changes. To avoid that you can:

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

    MDN warns:

    Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a reference to the object, which is not necessarily the 'value' of the object at the moment in time you call console.log(), but it is the value of the object at the moment you open the console.

提交回复
热议问题