Last active
March 9, 2018 02:06
-
-
Save yy-dev7/2d56b6e4d43654f212f252dbd3e3ffd8 to your computer and use it in GitHub Desktop.
deep clone
This file contains 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 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