美文网首页
浅谈深拷贝

浅谈深拷贝

作者: Michael113c | 来源:发表于2020-08-16 10:27 被阅读0次

    1.JSON方法实现

    //_tmp和result是相互独立的,没有任何联系,有各自的存储空间。
    let deepClone = function (obj) {
        let _tmp = JSON.stringify(obj);//将对象转换为json字符串形式
        let result = JSON.parse(_tmp);//将转换而来的字符串转换为原生js对象
        return result;
    };
    
    let obj1 = {
        mike: {
            age: 20,
            class: 1502
        },
        bob: {
            age: 21,
            class: 1501
        }
    };
    
    let test = deepClone(obj1);
    console.log(test);
    

    undefined、function、symbol 会在转换过程中被忽略

    If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array). JSON.stringify can also just return undefined when passing in "pure" values like JSON.stringify(function(){}) or JSON.stringify(undefined).

    2.for…in实现遍历和复制

    function deepClone(source){
      const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象
      for(let keys in source){ // 遍历目标
        if(source.hasOwnProperty(keys)){
          if(source[keys] && typeof source[keys] === 'object'){ // 如果值是对象,就递归一下
            targetObj[keys] = source[keys].constructor === Array ? [] : {};
            targetObj[keys] = deepClone(source[keys]);
          }else{ // 如果不是,就直接赋值
            targetObj[keys] = source[keys];
          }
        } 
      }
      return targetObj;
    }
    

    3.用数组的Array.prototype.forEach进copy

    let deepClone = function (obj) {
        let copy = Object.create(Object.getPrototypeOf(obj));
        let propNames = Object.getOwnPropertyNames(obj);
        propNames.forEach(function (items) {
            let item = Object.getOwnPropertyDescriptor(obj, items);
            Object.defineProperty(copy, items, item);
    
        });
        return copy;
    };
    
    let testObj = {
        name: "weiqiujuan",
        sex: "girl",
        age: 22,
        favorite: "play",
        family: {brother: "wei", mother: "haha", father: "heihei"}
    }
    let testRes2 = deepClone(testObj);
    console.log(testRes2);
    

    相关文章

      网友评论

          本文标题:浅谈深拷贝

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