user1 user1 - 3 years ago 92
Javascript Question

Array set by reference/set by value

Note: I assume this question has been asked a million times before but I didn't know what to search for.
The question is very simple. Array in javascript seems to be set by reference. How can i set it by value. Meaning, even if I empty the array a, I want array b to be the copy of a i.e., I want

alert(b)
to alert
['1','2','3']


var a = ['1','2','3'];
var b = [];
b = a;
a.length = 0;
alert(b);


here is a jsfiddle http://jsfiddle.net/e5mQM/

Answer Source

Yes, setting a = b; will make both variables point to the same array / object, so you have to copy the array instead of just referencing it :

b = a.slice();

javascripts slice() method returns a new array sliced based on the parameters given, and if called without parameters it will return a new shallow copy of the entire array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download