高频面试手写代码练习2--深复制

普通方法:1.JSON.parse(JSON.stringify(obj))   //不能复制function、正则、Symbol 、 循环引用报错(obj.test=obj)、相同的引用会被重复复制

                   2.lodash的方法  _.cloneDeep(obj)    //常用

                  3.面试中经常会遇到手写实现深复制

function isObject(obj) {
  return typeof obj === 'object' && obj != null;
}
function deepCopy(source){
  // 判断如果参数不是一个对象,返回改参数
  if(!isObject(source)) return source;
  // 判断参数是对象还是数组来初始化返回值
  let res = Array.isArray(source)?[]:{};
  // 循环参数对象的key
  for(let key in source){
    // 如果该key属于参数对象本身
    if(Object.prototype.hasOwnProperty.call(source,key)){
      // 如果该key的value值是对象,递归调用深拷贝方法进行拷贝
      if(isObject(source[key])){
        res[key] = deepCopy(source[key]);
      }else{
        // 如果该key的value值不是对象,则把参数对象key的value值赋给返回值的key
        res[key] = source[key];
      }
    }
  }
  // 返回返回值
  return res;
};

猜你喜欢

转载自blog.csdn.net/qq_33168578/article/details/114270029