xsss
xsss

Reputation: 81

JavaScript Copy Array By Value

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

Upvotes: 0

Views: 144

Answers (2)

Hew Wolff
Hew Wolff

Reputation: 1509

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.

Upvotes: 1

Frank B
Frank B

Reputation: 3697

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?

Upvotes: 1

Related Questions