Console.log() Displays Altered Array Values Prematurely
In programming, we frequently manipulate variables and log their values to the console to track changes. However, in the case of arrays, we encounter an unexpected behavior where console.log() outputs modified values of the array even before the changes are made.
This phenomenon can be observed in the following code snippet:
var A = [2, 1]; var C = A; console.log(C); // [1, 2] A.sort(); console.log(C); // [1, 2]
In this example, we have an array A with two elements that is assigned to another variable C. When we log C, it initially displays the original values [1, 2]. However, when we call the sort() method on A, we see that C also shows the sorted values [1, 2], even though the changes were applied to A.
Understanding the Behavior
This behavior occurs because console.log() is passed a reference to the object instead of a copy of its value. When you log an array, the console displays a reference to the array in memory, which is updated as the array changes.
To illustrate this, consider the following modified code:
var A = [2, 1]; var C = JSON.parse(JSON.stringify(A)); console.log(C); // [1, 2] A.sort(); console.log(C); // [2, 1]
By converting the array A to a JSON string and then back to an array, we create a new object in memory. This means that C now holds a copy of A's original values. When we sort A, C remains unchanged because it is a separate object.
MDN's Warning
This behavior is particularly relevant in modern versions of browsers like Chrome and Firefox:
MDN warns: ... at the moment you open the console.
This means that the logged value displayed in the console may not represent the actual value of the object at the time it was logged. Instead, it may show the value from when the console was first opened, which can lead to confusion.
Conclusion
When working with arrays, it is important to be aware of the reference-passing behavior of console.log(). If you want to log the actual values of arrays without the risk of premature changes, consider using the JSON.parse() and JSON.stringify() methods to create a deep copy of the array first.
The above is the detailed content of Why Does `console.log()` Show Altered Array Values Before the Changes Are Applied?. For more information, please follow other related articles on the PHP Chinese website!