1

I think this is just me not understanding part of how JavaScript works. Let's say I have an array, call it arr1, with 6 ints in it, [1,2,3,4,5,6]. If I make a new array:

var arr2 = arr1

(for the purpose of maintaining an unchanged copy of arr1), when I change arr1 the changes are reflected in arr2.

Basically, I am manipulating arr1. For testing purposes I wanted to have an unchanged copy of arr1 so that when I'm done I can console.log them both out on my web page and see the differences in them. But again, when I make changes in arr1, that change is reflected in arr2.

Can anyone explain why this happens and maybe a way around it? I'm more interested in why this happens than how to fix it.

One approach is to make arr2 a separate array, and use a for loop to populate it with arr1's data

for(int i = 0; i < arr1.length; i++) arr2[i] = arr1[i]

but, if the array was huge, that might be expensive. Any help is appreciated.

SethO
  • 2,703
  • 5
  • 28
  • 38
user1759942
  • 1,322
  • 4
  • 14
  • 33

3 Answers3

8

When you assign non-primitives (such as arrays), you're not making a copy. You're creating another reference to the same array.

If you want to copy an array:

var arr2 = arr1.slice();
// or
var arr2 = arr1.concat();

More reading: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
3

Objects are passed by reference, not by value.

To create a copy of the array, try:

var arr2 = arr1.slice(0);
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

Javascript is dealing with arrays by reference, so your arr1 and arr2 are actually pointing at the same array.

What you probably want to do is clone the array, which you can do with slice

var arr2 = arr1.slice(0);
WildCrustacean
  • 5,896
  • 2
  • 31
  • 42