美文网首页
实现深拷贝的两种方式

实现深拷贝的两种方式

作者: 海之深处爱之港湾 | 来源:发表于2021-05-08 11:14 被阅读0次
// 第一种
const a = {};
const b = JSON.parse(JSON.stringfy(a));

// 第二种
function clone(obj, hash = new WeakMap()) {
  // 判断是否为 null 或者 typeof 返回类型是否为 object
  if (obj == null || typeof obj !== "object") return obj;
  else if (obj instanceof Date) return new Date(obj);
  else if (obj instanceof RegExp) return new RegExp(obj);
  
  // 判断集合是否有这个属性,有则直接 return obj
  if(hash.has(obj)) return hash.get(obj)
  const newObj = new obj.constructor();
    
  // 将属性和拷贝后的值作为一个map
  hash.set(obj, newObj);
    
  // 遍历 obj
  for (let key in Object.getOwnPropertyDescriptors(obj)) {
      // 过滤掉原型身上的属性
      if (obj.hasOwnProperty(key)) {
        // 递归拷贝
        newObj[key] = clone(obj[key], hash);
      }
    
  }
  return newObj;
}

相关文章

网友评论

      本文标题:实现深拷贝的两种方式

      本文链接:https://www.haomeiwen.com/subject/mshudltx.html