Skip to content

Instantly share code, notes, and snippets.

@yy-dev7
Last active March 9, 2018 02:06
Show Gist options
  • Save yy-dev7/2d56b6e4d43654f212f252dbd3e3ffd8 to your computer and use it in GitHub Desktop.
Save yy-dev7/2d56b6e4d43654f212f252dbd3e3ffd8 to your computer and use it in GitHub Desktop.
deep clone
function deepClone() {
let copy
// 处理3个简单的类型, null 或者 undefined
if (obj === null || typeof obj !== 'object') {
return obj
}
if (obj instanceof Date) {
copy = new Date()
copy.setTime(obj.getTime())
return copy
}
if (obj instanceof Array) {
copy = []
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = clone(obj[i])
}
return copy
}
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) {
copy[attr] = clone(obj[attr])
}
}
return copy
}
throw new Error("Unable to copy obj! Its type isn't supported.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment