Skip to content

Instantly share code, notes, and snippets.

@lqt0223
Last active April 7, 2017 03:49
Show Gist options
  • Save lqt0223/57a9020fc9a879ab33043aeba0a36dd6 to your computer and use it in GitHub Desktop.
Save lqt0223/57a9020fc9a879ab33043aeba0a36dd6 to your computer and use it in GitHub Desktop.
17 Deep copy in JavaScript
// You are welcome to have a test on this function to check if it supports deep copy for very complex nested objects.
function deepCopy(o){
if(typeof o === "object" && o !== null){
var _o = new o.constructor();
for(var k in o){
_o[k] = deepCopy(o[k]);
}
return _o;
}else{
return o;
}
}
// test1
var obj = {a: [2,3,4,5]}
var copied = deepCopy(obj);
copied.a.push(2);
console.log(obj);
console.log(copied);
console.log("----");
// test2
var obj = {a: null, b: {}, c:[{d: []}]}
var copied = deepCopy(obj);
copied.c[0].d.push(2);
console.log(obj.c[0]);
console.log(copied.c[0]);
console.log("----");
// test3
var obj = [2,3,[4,5],[6],{a:7},[],{}];
var copied = deepCopy(obj);
copied.push(8);
console.log(obj);
console.log(copied);
console.log("----");
// test4
var obj = {a:{b:{c:1,d:2},e:3}};
var copied = deepCopy(obj);
copied.a.e = 4;
console.log(obj);
console.log(copied);
console.log("----");
// test5
var obj = 2;
var copied = deepCopy(obj);
copied = 4;
console.log(obj);
console.log(copied);
console.log("----");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment