Home >Web Front-end >JS Tutorial >Why Does `console.log()` Seem to Show Altered Array Values Before Modification in JavaScript?
Console Outputs Altered Array Value Before Modification
In JavaScript, variables are typically passed by reference, meaning that changes made to the variable after it has been assigned to another variable will be reflected in both variables. This behavior is often observed when console.log() is used to display the value of a variable.
For instance, consider the following code:
let A = [2, 1]; let C = A; console.log(C); // [1, 2]
In this example, variable C is assigned a reference to the array stored in variable A. When console.log(C) is executed, it outputs the array's current value, which is [1, 2]. However, this value may not be up-to-date if the original array A is modified later on.
A.sort(); console.log(C); // [1, 2]
Upon executing the sort() method on array A, its elements are sorted in-place. Since array C holds a reference to the same object, the output of console.log(C) remains [1, 2]. This is because console.log() displays the current value of the object at the time of execution, not a static value.
To avoid this unexpected behavior and ensure that console.log() outputs accurate values, you can either use:
console.log(JSON.parse(JSON.stringify(C)));
Or, as MDN suggests:
Object.assign({}, A)
The above is the detailed content of Why Does `console.log()` Seem to Show Altered Array Values Before Modification in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!