You need to use recursion
var a = [1,2,[3,4,[5,6]]]; Array.prototype.clone = function() { var arr = []; for( var i = 0; i < this.length; i++ ) { // if( this[i].constructor == this.constructor ) { if( this[i].clone ) { //recursion arr[i] = this[i].clone(); break; } arr[i] = this[i]; } return arr; } var b = a.clone() console.log(a); console.log(b); b[2][0] = 'a'; console.log(a); console.log(b); /* [1, 2, [3, 4, [5, 6]]] [1, 2, [3, 4, [5, 6]]] [1, 2, [3, 4, [5, 6]]] [1, 2, ["a", 4, [5, 6]]] */
Any other objects in the source array will be copied by reference, although
meouw Feb 19 '10 at 8:17 2010-02-19 08:17
source share