实现对象的深拷贝

代码如下

 const obj = {
       name: 'zhangsan',
       age: 18,
       address: {
         email: '[email protected]',
         phone: '10086',
         address2: {
           age: 20
         }
       }
     }
     const obj2 = deepCope(obj);
     obj.address.email = 'lisi'
     console.log(obj)
     console.log(obj2)
     function deepCope(obj = {}) {
      if (obj !== 'obj' || obj == null) {
        return obj
      }
      //初始化结果
       let result
      if (obj instanceof Array) {
         result = []
      }else {
        result = {}
      }
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          result[key] = deepCope(obj[key]);
        }
      }
      return result
     }

你可能感兴趣的:(实现对象的深拷贝)