Leggy
Leggy

Reputation: 682

New array overwriting global array

I have a global array like:

var myArray = [];

And it has various elements in it. I need to create a new array with the same contents and then reverse it like this:

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

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

What am I doing wrong?

Thanks!

Upvotes: 3

Views: 65

Answers (1)

Sampath Liyanage
Sampath Liyanage

Reputation: 4896

It's because both your arrays are referenced to the same object. To get rid of it you have to clone it with slice..

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

Upvotes: 5

Related Questions