Skip to content

Instantly share code, notes, and snippets.

@hara-y-u
Created October 19, 2011 02:58
Show Gist options
  • Save hara-y-u/1297381 to your computer and use it in GitHub Desktop.
Save hara-y-u/1297381 to your computer and use it in GitHub Desktop.
clone Array recursively
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