Home >Web Front-end >JS Tutorial >How to Create Truly Independent Array Copies in JavaScript?
Duplicating Arrays for Independence in JavaScript
Copying arrays in JavaScript can lead to unexpected behavior due to reference-based assignment. When assigning one array to another (e.g., var arr1 = ['a', 'b', 'c']; var arr2 = arr1;), both variables point to the same array object. This means modifications to either variable affect the other.
Creating Independent Arrays
To create truly independent arrays, we need to duplicate the original array's contents instead of assigning the reference. The slice() method provides a straightforward solution:
let oldArray = [1, 2, 3, 4, 5]; let newArray = oldArray.slice();
In this example, newArray becomes a new array with the same values as oldArray. However, the two arrays are now separate objects and modifications to one do not affect the other. The slice() method effectively duplicates the values of the original array into a new independent instance.
The above is the detailed content of How to Create Truly Independent Array Copies in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!