1

sorry very basic question I'm new.

If I have an array and pass it to a new variable (newArray = oldArray) then remove an element from newArray, it seems to also effect oldArray.

my guess is that it's simply creating a new reference to the same variable, so that data that was stored in oldArray now has two identifiers?

If so how do I actually pass the elements from oldArray into newArray so that newArray is independent from oldArray?

Thanks in advance

jsnewb
  • 45
  • 7
  • Maybe the answer is the same... but I did a search and didn't find the answer. This is because I wasn't aware there is a difference between passing by value and by reference, as I'm sure a lot of newbs like me would be unaware, making my question searchable to us newbs :P – jsnewb Apr 15 '13 at 21:20

4 Answers4

1

my guess is that it's simply creating a new reference to the same variable, so that data that was stored in oldArray now has two identifiers?

Right, both your new variable and your old one are pointing to the same array. Operations on the array through one reference (variable) are naturally visible through the other one, since there is just one array.

To avoid this, you'd have to make a copy of the array. There are several ways to do that, one of which is to use slice:

var newArray = oldArray.slice(0);

slice returns a shallow copy of an array starting at the given index. If you give it the index 0, it copies the entire array.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

The quickest way is to use an array function to return a new array instance. Typically, I use:

var newArray = oldArray.slice(0);
Lanny
  • 11,244
  • 1
  • 22
  • 30
0

In that case you have to clone the array using the slice method:

newArray = oldArray.slice(0);
tomor
  • 1,765
  • 2
  • 16
  • 21
0

As you've learned, when you copy an array variable, you copy a reference to the original.

Here's one idom to make a real copy - request a slice from the first element

 var newArray = oldArray.slice(0);
Paul Dixon
  • 295,876
  • 54
  • 310
  • 348