Skip to content

Instantly share code, notes, and snippets.

@Cycymomo
Last active December 19, 2015 06:18
Show Gist options
  • Save Cycymomo/5910107 to your computer and use it in GitHub Desktop.
Save Cycymomo/5910107 to your computer and use it in GitHub Desktop.
deep copy object or array in Javascript
function deepCopy(obj) {
if (Object.prototype.toString.call(obj) === '[object Array]') {
var len = obj.length, out = new Array(len), i = 0;
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;
}
/* test case
var a = [[1], [2], [3]];
var b = deepCopy(a);
console.log(a); // [[1], [2], [3]]
console.log(b); // [[1], [2], [3]]
console.log(a === b); // false
b[0][0] = 99;
console.log(a); // [[1], [2], [3]]
console.log(b); // [[99], [2], [3]]*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment