Home >Web Front-end >JS Tutorial >How Can I Create a Truly Independent Copy of a JavaScript Array?

How Can I Create a Truly Independent Copy of a JavaScript Array?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-20 20:18:11437browse

How Can I Create a Truly Independent Copy of a JavaScript Array?

Creating a Truly Independent Array Copy

JavaScript's array copying behavior can be confusing, as shown in the example:

var arr1 = ['a', 'b', 'c'];
var arr2 = arr1;
arr2.push('d'); // arr1 now becomes ['a', 'b', 'c', 'd']

To create truly independent arrays, you need to use a method that creates a new array instead of referencing the original one. The solution lies in using the slice() method:

let oldArray = [1, 2, 3, 4, 5];

let newArray = oldArray.slice();

console.log({newArray});

The slice() method returns a new array with the same elements as the original array, but without modifying the original array. Hence, any changes made to the new array will not affect the old array, ensuring independence.

The above is the detailed content of How Can I Create a Truly Independent Copy of a JavaScript Array?. 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