深拷贝
小于 1 分钟
实现
function deepClone(source) {
if (typeof source !== "object" || source === null) {
return source;
}
if (source instanceof Date) return new Date(source);
if (source instanceof Set) return new Set(Array.from(source));
if (source instanceof Map) return new Map(source.entries());
const target = Array.isArray(source) ? [] : {};
for (const key in source) {
// 不克隆原型上的属性和方法
if (Object.prototype.hasOwnProperty.call(source, key)) {
// 解决循环引用问题
if (source[key] === source) {
target[key] = source;
} else {
target[key] = deepClone(source[key]);
}
}
}
return target;
}