cloneDeep

  • 处理对象的循环引用
  • 处理 DOM节点
  • 处理 构造函数
  1. export function cloneDeep(value, hash = new WeakMap()) {
  2. // 如果是空值,或简单类型,就直接返回
  3. if(!value || typeof value !== 'object') return value;
  4. // 如果 hash表里有这个对象,就返回这个对象,不要循环引用
  5. if(hash.get(value)) return hash.get(value);
  6. // 是不是构造函数 new String(10), new RegExp(/\s+/)
  7. const typesArray = [Number, String, Boolean, Date, RegExp];
  8. const instance = typesArray.find(type => value instanceof type);
  9. if(instance) {
  10. return new instance(value);
  11. }
  12. // 是不是 DOM节点
  13. if(value.nodeType && typeof value.cloneNode === 'function') {
  14. return value.cloneNode(true); // 深拷贝
  15. }
  16. const temp = new value.constructor();
  17. hash.set(value, temp);
  18. for(const key in object) {
  19. if(value.hasOwnProperty(key)) {
  20. temp[key] = cloneDeep(value[key], hash);
  21. }
  22. }
  23. return temp;
  24. }

JSON.parse

只能处理简单的数据类型

  • array, object,
  • string, boolean, number,

缺点:

  • 不能处理循环引用
  • 不能拷贝函数,
  • 不能拷贝构造函数