深拷贝

// 深拷贝
    function deepClone(obj={}){
      if (typeof obj !== "object" || obj == null) {
        // obj是null,或者不是数组对象,直接返回
        return obj;
      }
      // 初始化返回结果
      let result;
      if (obj instanceof Array) {
        result = []
      } else {
        result = {}
      }
      
      for (let key in obj){
        // 保证key不是原型的属性
        if(obj.hasOwnProperty(key)){
          // 递归
          result[key] = deepClone(obj[key])
        }
      }
      // 返回结果
      return result;
    }
const obj1 = {
      name: 'ming',
      address:{
        city: 'beijing'
      },
      arr:[1,2,3]
    }
    const obj2 = deepClone(obj1);
    obj2.address.city = 'hangzhou'
    console.log(obj1.address.city); // beijing

 

posted @ 2020-06-21 00:39  两只小老虎  阅读(183)  评论(0编辑  收藏  举报