手写js深拷贝

4 阅读1分钟

首先判断值类型还是引用类型 其次再判断是数组还是对象 最后用递归进行处理

function deepClone (obj = {}) {
  if (typeof obj !== 'object' || typeof obj == null) {
    return obj;
  }
  let result;
  if (obj instanceof Array) {
    result = [];
  } else {
    result = {};  
  }
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      result[key] = deepClone(obj[key]);
    }
  }
  return result;
}