cloneDeep
- 处理对象的循环引用
- 处理 DOM节点
- 处理 构造函数
export function cloneDeep(value, hash = new WeakMap()) {// 如果是空值,或简单类型,就直接返回if(!value || typeof value !== 'object') return value;// 如果 hash表里有这个对象,就返回这个对象,不要循环引用if(hash.get(value)) return hash.get(value);// 是不是构造函数 new String(10), new RegExp(/\s+/)const typesArray = [Number, String, Boolean, Date, RegExp];const instance = typesArray.find(type => value instanceof type);if(instance) {return new instance(value);}// 是不是 DOM节点if(value.nodeType && typeof value.cloneNode === 'function') {return value.cloneNode(true); // 深拷贝}const temp = new value.constructor();hash.set(value, temp);for(const key in object) {if(value.hasOwnProperty(key)) {temp[key] = cloneDeep(value[key], hash);}}return temp;}
JSON.parse
只能处理简单的数据类型
- array, object,
- string, boolean, number,
缺点:
- 不能处理循环引用
- 不能拷贝函数,
- 不能拷贝构造函数
