Skip to content

Instantly share code, notes, and snippets.

@xwartz
Last active November 16, 2015 16:05
Show Gist options
  • Save xwartz/d5eb31f25d097191238b to your computer and use it in GitHub Desktop.
Save xwartz/d5eb31f25d097191238b to your computer and use it in GitHub Desktop.
underscorejs 深拷贝实现
// 普通字面量对象的深拷贝
_.cloneDeep = function (obj) {
if (typeof(obj) != 'object' || obj == null) return obj;
if(obj instanceof Date) {
return new Date(obj.getTime());
}
var newObj = {};
// 数组
if(Object.prototype.toString.call(obj) === '[object Array]') {
newObj = [];
}
for (var i in obj) {
newObj[i] = _.cloneDeep(obj[i]);
}
return newObj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment