Reputation: 11164
I have two arrays
arr1 = new Array();
arr2 = new Array();
If i do the following:
arr1 = arr2;
in javascript is this assigning by value or by reference? What i mean is, after doing the above, will further changes in arr2 affect arr1's content and also the other way around?
Upvotes: 2
Views: 419
Reputation: 1701
Here is a clone function I wrote...
/**
* Clone an Object or Array.
*
* @param {Object}
* obj the Object or Array that should be cloned
* @param {Boolean}
* deep if true also clones the elements of an Object or Array,
* default is true
* @return
* @type Object
*/
function cloneObject(obj, deep) {
try {
deep = !deep ? false : true;
if (obj.constructor === Object) {
var nObj = {}, elem = null;
for (elem in obj) {
if (obj.hasOwnProperty(elem)) {
nObj[elem] = deep ? cloneObject(obj[elem]) : obj[elem];
}
}
return nObj;
}
if (obj.constructor === Array) {
var nArr = [], i = 0;
for (i = 0; i < obj.length; i++) {
nArr[i] = deep ? cloneObject(obj[i]) : obj[i];
}
return nArr;
}
} catch (e) {
console.error("cloneObject(", arguments, ") >", e);
}
return obj;
};
Upvotes: 0
Reputation: 11588
In javascript arrays are objects. So, in a nutshell, yes, you will be passing a reference.
arr1 = new Array();
arr2 = new Array();
arr1 = arr2;
arr1.push('test');
alert(arr2[0]);//test
if you want to pass it by value, you should make a clone function like:
function cloneValue(value){
if (typeof value != 'object')
return value;
else {
var newObj = {};
for (var prop in value){
newObj[prop] = value[prop];
}
return newObj;
}
}
function cloneArray(array){
var newArray = [];
for(var i = 0; i < array.length; i++){
newArray[i] = cloneValue(array[i]);
}
return newArray;
}
var arr2 = cloneArray(arr1);
this still has a perk, if the values in the array are not primitive, they are going to be passed by reference again...
I edited the code...
Upvotes: 2
Reputation: 12633
Why not create a test case yourself e.g.
arr1 = new Array();
arr2 = new Array();
arr1.push('bob');
arr2.push('joan');
alert(arr1); // Shows "bob"
alert(arr2); // Shows "joan"
arr1 = arr2;
arr2.push("jacob");
arr1.push("goliath");
alert(arr1); // Shows "joan", "jacob", "goliath"
alert(arr2); // Also shows "joan", "jacob", "goliath"
So arr1 refers to arr2 (after assignment of the arr2 to arr1) and contains "joan". Then we push "jacob" and "goliath" but the last alert shows "joan", "jacob" and "goliath" - because Arrays are objects and arr1 and arr2 are pointing to the same Object when the program ends.
Upvotes: 3
Reputation: 64933
Your case sets arr1 with object/array held by arr2. For that reason, now any change in arr1, like setting an index, will modify the array previously created in arr2.
Upvotes: 2