Home >Web Front-end >JS Tutorial >How Do I Create a True Copy of a JavaScript Array?

How Do I Create a True Copy of a JavaScript Array?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-30 11:03:10931browse

How Do I Create a True Copy of a JavaScript Array?

Cloning Arrays in JavaScript

In JavaScript, copying an array by assignment creates a reference to the original array rather than an independent copy. This can lead to unexpected behavior, as demonstrated in the following code snippet:

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

To create an independent copy of an array, use the slice() method:

let oldArray = [1, 2, 3, 4, 5];
let newArray = oldArray.slice();
console.log({newArray}); // [1, 2, 3, 4, 5]

The slice() method returns a shallow copy of the original array, creating a new array with the same elements but no direct reference to the original array. This ensures that changes made to the new array do not affect the original array.

The above is the detailed content of How Do I Create a True 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