0

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.

2

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

@Kolink not even a second. I see 2012-11-21 18:44:50Z for both our answers. :)
Thanks both of you for the quickest answers.
3

Objects are passed by reference, not by value.

To create a copy of the array, try:

var arr2 = arr1.slice(0);

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.