Asked 7 years ago
28 Nov 2016
Views 929
jassy

jassy posted

issue in copy one array to another array by value in JavaScript


var first = ['my','mind','is'];
var second = first ;
second.push('gone');  //Now, first= ['my','mind','is','gone']


so when i do copy from one array to another by "=" . and do change on second array it reflect in the first array.

so am i doing wrong anything
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

its called copy by reference. here first variable 's reference stored in second so
1. if you do any change in second it goes to first variable 's value.


var first = ['my','mind','is'];
var second = first ;
second.push('gone');  //Now, first= ['my','mind','is','gone'] and second=  ['my','mind','is','gone']


2. if you do any change in first it goes to second variable 's value


var first = ['my','mind','is'];
var second = first ;
first.push('gone');  //Now, first= ['my','mind','is','gone'] and second=  ['my','mind','is','gone']


because there are both same . its clone of each other , reside in same memory with differ name .


so if you want to copy one array to another array
1.copy each value one array to another array by forEach or for or while


var first = ['my','mind','is'];
//var second = first ;
var second = [];
console.log(second);// second array is empty 
first.forEach(function(item,index){
      second.push(item);// we copied each item to second arrray 
});
console.log(first);// first= ['my','mind','is']
console.log(second);// second= ['my','mind','is']
second.push('gone'); 
console.log(first); // but still first array is remain unchanged first = ['my','mind','is']
console.log(second); //Now, second= ['my','mind','is','gone']
first.push('brilliant');
console.log(first);//Now, second= ['my','mind','is','brilliant']



Post Answer