Create one array exactly equal to another

I have two arrays:

var array1 = [1, 2, 3]; var array2 = [4, 5, 6]; 

I want array 1 to be exactly equal to array 2. I was told that I just can't do:

 array1 = array2; 

If I cannot do this, how can I make array1 equal to array2?

thanks

+7
javascript arrays
source share
3 answers

If you just need a copy of the elements of the array, you can simply use the slice as follows:

 a = [1,2,3] copyArray = a.slice(0) [1 , 2 , 3] 

As for why you shouldn't use assignment, look here:

 a = [1,2,3] b = a a.push(99) a [1,2,3,99] b [1,2,3,99] 

If you copy an array, you do not have this problem:

  a = [1,2,3] b = a.slice(0) a.push(888) a [1,2,3,888] b [1,2,3] 
+12
source share

For a deep copy of your array, do this ( LINK ):

 function deepCopy(obj) { if (Object.prototype.toString.call(obj) === '[object Array]') { var out = [], i = 0, len = obj.length; for ( ; i < len; i++ ) { out[i] = arguments.callee(obj[i]); } return out; } if (typeof obj === 'object') { var out = {}, i; for ( i in obj ) { out[i] = arguments.callee(obj[i]); } return out; } return obj; } 
0
source share

This will do the trick:

 var clone = originalArray.slice(0); 
0
source share

All Articles