New array overwriting the global array

I have a global array like:

var myArray = [];

      

And there are various elements in it. I need to create a new array with the same content and then modify it like this:

newArray = myArray;
newArray = newArray.reverse();

      

However, when I do this, it changes both myArray and newArray.

What am I doing wrong?

Thank!

+3


source to share


1 answer


This is because both arrays refer to the same object. To get rid of it, you must clone it with a slice.



var myArray = [1,2];
var newArray = myArray.slice(0)
newArray.reverse();

      

+5


source







All Articles