JS深拷贝递归实现

方法1.要提前声明一个对象

var A = {
    name: "martin",
    data: {
      num: 10
    },
    arr:[1,2,3],
    say: function () {
      console.log("say");
    },
    null:{}
  };
  var B = {};
  //递归赋值
  function deepCopy(A, B) {
    for (item in A) { //for in……如果遍历数组则会返回下标,如果遍历对象则返回属性Key值,所以数组下A[item]是一个值,对象B[item]是value值
      if ((typeof A[item]) == "object" || (typeof A[item]) == "Array") {
        B[item] = A[item].constructor === Array ? [] : {}//js的每个对象constructor指向它的构造函数
        deepCopy(A[item], B[item]);
      } else {
        B[item] = A[item]; //基本数据赋值过程相当于深拷贝
      }
    }
  }
  deepCopy(A, B);

方法二:直接返回一个深拷贝的对象

function deepClone(source){
  //js的每个对象constructor指向它的构造函数
  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;
}
穷则独善其身,达则兼济天下……
原文地址:https://www.cnblogs.com/hmy-666/p/14440795.html