0

I have created an array and received another from a php file. The data is fine but when i try to copy one array to another, it seems like when i change arr1 then arr2 is also changed.

It is being copied "by reference" and not "by value" as i need

I also tried slice() butit doesn't work, The variable does not being copied at all, not even "by reference" in that way.

// arr1[0] = "Hey";//this array is coming from another file and the data is fine
var arr2 = [];

arr2[0] = arr1[0];
arr2[0] += "1"; // right now arr1 and arr2 both has "Hey1" in them.

Any ideas? Thank You

4
  • Are you quite sure that both those arrays have "Hey1" in them? Commented Jun 1, 2015 at 21:49
  • It doesn't do that for me: jsfiddle.net/barmar/sxochn11 Commented Jun 1, 2015 at 21:51
  • 1
    This would happen if you did arr2 = arr1, not the code you showed. Commented Jun 1, 2015 at 21:52
  • I think your example doesn't reflect your actual program enough. Are you, by chance, substituting objects in your real program with strings here? Because what you are showing is not how Javascript works: fiddle Commented Jun 1, 2015 at 21:52

2 Answers 2

1

An array is an object in Javascript. As you might know objects are copied by reference. You could take a look here: What is the most efficient way to deep clone an object in JavaScript?

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

Comments

1

You can do a deep, rather than a shallow, copy of an array of strings like this:

var arr2 = [], i = 0;
for (i = 0; i < arr1.length; i++) {
    arr2[i] = String(arr1[i]);
}

EDITED: oops, swapped deep and shallow.

1 Comment

He's not copying the array anywhere.

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.