I am making an app in which an algorithm is run on an array. Because the contents of the array will change during the execution of the algorithm, I’m storing the array contents to another array beforehand – performing the ‘if’ statements on the source array but updating the temporary array, then equating them afterwards.
The problem is that after running the algorithm, the two arrays are still identical. It seems that updating the temporary array automatically updates the source array.
I’ve created this jsfiddle to demonstrate:
var a = new Array( 0 , 1 , 2 );
var b = a;
b[1]=3;
document.write( (a[1]==b[1]) );
//Should show 'false' as this will not be correct
The code above returns “True”. Is this normal behaviour? How can I overcome this?
That is normal behaviour, when copying array you are actually making a reference, so when you do
var b = athat means instead of copying value you are just copying the referenceif you want to shallow copy an array (array with only one depth level) then you can use simple method like this:
But if you want to deep copy an array (array with 2 or more depth level) then you can use below method for that:
For use of both of these methods check this jsFiddle