Copying Arrays in JavaScript: Preserving Independence
Copying an array in JavaScript can be a tricky business. Simply assigning one array to another, as shown in the example:
var arr1 = ['a', 'b', 'c']; var arr2 = arr1; arr2.push('d');
Will result in both arrays referencing the same underlying array object. This means any changes made to one array will be reflected in the other. To achieve independence, it's crucial to create a new array object.
Solution: The Slice Method
One effective way to copy an array independently is to use the slice() method. This method returns a shallow copy of the original array, preserving the values but creating a distinct array object in memory.
let oldArray = [1, 2, 3, 4, 5]; let newArray = oldArray.slice(); console.log({ newArray });
In this example, the newArray variable now holds an independent copy of the oldArray values. Pushing an element to newArray won't affect oldArray, demonstrating their independence.
The above is the detailed content of How to Create Independent Array Copies in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!