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.