Created
October 19, 2011 02:58
-
-
Save hara-y-u/1297381 to your computer and use it in GitHub Desktop.
clone Array recursively
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function recurClone(input) { | |
var output = void(0), i, len; | |
if(input instanceof Array) { | |
output = []; | |
for(i=0,len=input.length; i<len; i++) { | |
output.push(recurClone(input[i])); | |
} | |
} else { | |
output = input; | |
} | |
return output; | |
} | |
var arr1 = [['foo', ['bar']], 'baz', { hoge: 'huga' }]; | |
var arr2 = recurClone(arr1); | |
console.log(arr1 === arr2); // false | |
console.log(arr1[0] === arr2[0]); // false | |
// replace reference of only Arrays (don't apply to primitives and other objects) | |
console.log(arr1[0][0] === arr2[0][0]); // true | |
console.log(arr1[0][1] === arr2[0][1]); // false | |
console.log(arr1[1] === arr2[1]); //true | |
console.log(arr1[3] === arr2[3]); //true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment