javascript copy an array
To copy an array in JavaScript, you can use the slice()
method or the spread operator (...
). Here's how you can do it:
Using the slice()
method:
const originalArray = [1, 2, 3, 4, 5];
const copiedArray = originalArray.slice();
Using the spread operator (...
):
const originalArray = [1, 2, 3, 4, 5];
const copiedArray = [...originalArray];
Both methods create a new array that is a copy of the original array. Any modifications made to the copied array will not affect the original array.
I hope this helps! Let me know if you have any further questions.