Home >Web Front-end >JS Tutorial >Why Does `console.log()` Show Unexpected Array Behavior in JavaScript?
Unexpected Behavior of console.log() with Arrays
In JavaScript, the console.log() function behaves unexpectedly when inspecting arrays. This behavior stems from the fact that console.log() is passed a reference to the array, rather than a copy of the value.
Example:
var A = [2, 1]; var C = A; console.log(C); // [1, 2] A.sort(); console.log(C); // [1, 2]
When we sort the array A, we expect the value of C to remain unchanged. However, this is not the case. The value of C changes to the sorted array [1, 2] as well.
Why does this happen?
Because console.log() is passed a reference to the array, any changes made to the original array are also reflected in the reference held by C. Therefore, when A is sorted, the output of C also changes.
How to avoid this behavior:
To avoid this unexpected behavior, we can use the following workaround:
console.log(JSON.parse(JSON.stringify(C)))
This converts the array C into a string using JSON.stringify(), then back into an array using JSON.parse(). This effectively creates a deep copy of the array, ensuring that any changes made to the original array are not reflected in the copy.
Browser Warning:
It's important to note that the Mozilla Developer Network (MDN) warns about this behavior in recent versions of Chrome and Firefox:
"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."
The above is the detailed content of Why Does `console.log()` Show Unexpected Array Behavior in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!