Home >Web Front-end >JS Tutorial >How to Create Independent Array Copies in JavaScript?

How to Create Independent Array Copies in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-20 12:27:17591browse

How to Create Independent Array Copies in JavaScript?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn