Home >Web Front-end >JS Tutorial >Why Do JavaScript Array Copies Change When the Original Changes?
Why Does Changing an Array in JavaScript Impact Copies?
In JavaScript, arrays are objects, and variables hold references to these objects rather than the objects themselves. This inheritance can lead to unexpected behavior when assigning new values to arrays.
Consider the example:
// Declare an array and its copy var myArray = ['a', 'b', 'c']; var copyOfMyArray = myArray; // Modify the copy of the array copyOfMyArray.splice(0, 1); // Display the values alert(myArray); // ['b', 'c'] alert(copyOfMyArray); // ['b', 'c']
By manipulating copyOfMyArray, we inadvertently modified myArray. This is because variables like myArray and copyOfMyArray point to the same underlying array object.
Arrays vs. Numbers
In contrast, when working with numbers like myNumber and copyOfMyNumber, each variable holds a copy of the value itself. Modifying one does not affect the other.
var myNumber = 5; var copyOfMyNumber = myNumber; // Decrement the copy of the number copyOfMyNumber--; // Display the values alert(myNumber); // 5 alert(copyOfMyNumber); // 4
Consequences and Workarounds
Understanding this behavior is crucial for proper object manipulation. If you truly need a distinct copy of the array, use the slice method to create a shallow copy:
var copyOfMyArray = myArray.slice(0);
However, it's worth noting that this shallow copy only duplicates the array's references to its elements. Any internal objects will still refer to the same original instances.
The above is the detailed content of Why Do JavaScript Array Copies Change When the Original Changes?. For more information, please follow other related articles on the PHP Chinese website!