如果你是应对面试,那你可以完全可以把这段代码背下来,hhh
function deepClone(obj, hash = new WeakMap()) {
if (obj === null) {
return null;
}
if (obj instanceof Date) {
return new Date(obj);
}
if (obj instanceof RegExp) {
return new RegExp(obj);
}
if (typeof obj !== "object") {
return obj;
}
//处理对象的循环引用
if (hash.has(obj)) {
return hash.get(obj);
}
const resObj = Array.isArray(obj) ? [] : {};
hash.set(obj, resObj);
Reflect.ownKeys(obj).forEach((key) => {
resObj[key] = this.deepClone(obj[key], hash);
});
return resObj;
}