// 深度克隆
function getType(target: unknown) {
return Object.prototype.toString.call(target).slice(8, -1);
}
function deepClone<T>(target: T): T {
const type = getType(target);
if (type === 'Array') {
const result: T = [];
target.forEach((value, index) => {
result[index] = deepClone(value);
});
return result;
}
if (type === 'Object') {
const result: T = {};
Object.keys(target).forEach((key) => {
result[key] = deepClone(target[key]);
});
return result;
}
if (type === 'RegExp') {
const reFlags = /\w*$/;
const result = new target.constructor(target.source, reFlags.exec(target));
result.lastIndex = target.lastIndex;
return result;
}
return target;
}
深拷贝一般来说不用关心内部实现的类型,抄一下lodash的类型即可。
lodash的cloneDeep类型:
所以这样写就可以了