Last active
February 13, 2018 13:45
-
-
Save dondevi/8ed0ff059a88ba8799f620c570808710 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 deepCopy (object, pairs = []) { | |
let copy = {}; | |
pairs.push([object, copy]); | |
for (let key in object) { | |
if (object.hasOwnProperty(key)) { | |
let value = object[key]; | |
if (Array.isArray(value)) { | |
value = value.slice(); | |
} | |
if ("[object Object]" === Object.prototype.toString.call(value)) { | |
let exsit = false; | |
for (let i = 0, pair = null; pair = pairs[i]; i++) { | |
if (value === pair[0]) { | |
value = pair[1]; | |
exsit = true; | |
break; | |
} | |
} | |
if (!exsit) { | |
value = deepCopy(value, pairs); | |
} | |
} | |
copy[key] = value; | |
} | |
} | |
return copy; | |
} |
This file contains hidden or 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
let root = { | |
name: "root", | |
array: [0], | |
function (v) { this.array.push(v) }, | |
}; | |
root.child = { | |
name: "child", | |
parent: root, | |
}; | |
root.grandchild = | |
root.child.child = { | |
name: "grandchild", | |
grandparent: root, | |
parent: root.child, | |
}; | |
root.self = root; | |
root.child.self = root.child; | |
root.grandchild.self = root.grandchild; | |
let copy = deepCopy(root); | |
copy.child.parent.array.push(1); | |
copy.self.name = "root copy"; | |
copy.child.name = "child copy"; | |
copy.child.child.name = "grandchild copy"; | |
console.log(root); | |
console.log(copy); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment