这段代码我明白了。我们复制 A 并将其称为 C。当 A 更改时,C 保持不变
var A = 1;
var C = A;
console.log(C); // 1
A++;
console.log(C); // 1
但是当 A 是数组时,情况就不同了。 C 不仅会改变,而且在我们接触 A 之前它就会改变
var A = [2, 1];
var C = A;
console.log(C); // [1, 2]
A.sort();
console.log(C); // [1, 2]
有人可以解释第二个例子中发生了什么吗?
最佳答案
Console.log()
被传递了一个对象的引用,因此控制台中的值随着对象的变化而变化。为避免这种情况,您可以:
console.log(JSON.parse(JSON.stringify(c)))
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.
关于javascript - console.log() 显示变量值实际变化前的变化值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11284663/