代码实现
const referenceTypes = {
'Date': Date,
'Function': Function,
'RegExp': RegExp,
'Error': Error
};
function getType(target) {
return Object.prototype.toString.call(target)?.match(/[a-zA-Z]*(?=\])/)[0];
}
function deepClone1(target, hash = new WeakMap()) {
if (target === null) return target
const type = getType(target);
if (referenceTypes[type]) {
return new referenceTypes[type](target);
}
if (typeof target !== 'object') return target;
if (hash.get(target)) return hash.get(target)
const cloneTarget = new target.constructor();
hash.set(target, cloneTarget);
Reflect.ownKeys(target).forEach((key) => {
cloneTarget[key] = deepClone(target[key], hash);
});
return cloneTarget;
}
运行截图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/81a468d59e3ae1747a4cb2edbbb32e69.png#pic_center)