最终形态
// 深拷贝
function deepCopy(data) {
if(data === undefined || data === null) return data;
let __copy;
if(data instanceof Date) __copy = new Date(data);
else __copy = new data.constructor();
for(let key in data) {
if(!data.hasOwnProperty(key)) continue;
let item = data[key];
if(item instanceof Object) {
__copy[key] = deepCopy(item);
} else {
__copy[key] = item;
}
}
return __copy;
}
// 深度合并
function deepAssign(origin, obj) {
if(arguments.length > 2) {
return deepAssign(deepAssign(arguments[0], arguments[1]), ...([].slice.call(arguments, 2)));
}
for(const key in obj) {
if(!Object.prototype.hasOwnProperty.call(obj, key)) ;
else {
let item = obj[key],
o = origin[key],
isObj = item instanceof Object,
isArr = item instanceof Array;
if(!o || o.constructor !== item.constructor) {
origin[key] = isArr ? [].concat(item) : isObj ? deepAssign({}, item) : item;
} else {
origin[key] = isArr ? o.concat(item) : isObj ? deepAssign(o, item) : item;
}
}
}
return origin;
}
网友评论