代码实现
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;
}
运行截图