Object.assign和展开运算符都是浅拷贝 如何实现一个深拷贝呢
- 要考虑传入变量为null和undefined的情况
- 要处理日期Date和正则RegExp的情况
- 不是引用类型的 直接返回
function deepClone(obj) {
if (obj == null) return obj; // 如果是null 或者undefined 直接返回
// 正则表达式或者日期对象 直接返回
if (obj instanceof Date) return new Date(obj);
if (obj instanceof RegExp) return new RegExp(obj);
// 不是对象直接返回
if (typeof obj !== 'object') return obj;
// 剩下的认为是对象或者数组 new它的constructor 获得一个新的数组或对象
let newObj = new obj.constructor();
// 遍历老对象 并设置新对象的key为老对象key对应的值
for (const key in obj) {
newObj[key] = deepClone(obj[key]);
}
return newObj;
}
let obj1 = { a: '1', b: { a: '2' } };
console.log(deepClone(obj1)); // { a: '1', b: { a: '2' } }
这样就实现了一个简单的深拷贝,但是存在缺陷,因为可能会有这样的代码出现
let obj1 = { a: '1', b: { a: '2' } };
obj1.c = obj1; // 循环引用
当出现循环引用时 执行拷贝时会抛错:
console.log(deepClone(obj1));
/**
function deepClone(obj) {
^
RangeError: Maximum call stack size exceeded
*/
为了解决这个问题 需要用到Set / Map 数据结构,这里使用WeakMap
- 维护一个WeakMap映射表hash,key存放老的obj,value存在新创建出来的newObj
- 如果hash中存在obj 说明已经存过了,直接返回
- 在递归的的时候,将hash传进去
优化后的终板代码:
function deepClone(obj, hash = new WeakMap()) {
if (obj == null) return obj; // 如果是null 或者undefined 直接返回
// 正则表达式或者日期对象 直接返回
if (obj instanceof Date) return new Date(obj);
if (obj instanceof RegExp) return new RegExp(obj);
// 不是对象直接返回
if (typeof obj !== 'object') return obj;
// 如果hash中已经有obj了 直接返回
if (hash.has(obj)) return hash.get(obj);
// 剩下的认为是对象或者数组 new它的constructor 获得一个新的数组或对象
let newObj = new obj.constructor();
// 把obj放到映射表中
hash.set(obj, newObj);
// 遍历老对象 并设置新对象的key为老对象key对应的值
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = deepClone(obj[key], hash);
}
}
return newObj;
}
测试一下:
let obj1 = { a: '1', b: { a: '2' } };
obj1.c = obj1;
console.log(deepClone(obj1));
/**
<ref *1> { a: '1', b: { a: '2' }, c: [Circular *1] }
*/