js手写浅深拷贝

function shallowCopy(obj) {
    
    
  let cloneObj = {
    
    };
  for (let i in obj) {
    
    
    cloneObj[i] = obj[i];
  }
  return cloneObj;
}

function deepCopy(obj) {
    
    
  let cloneObj;
  if (typeof obj === "object") {
    
    
    cloneObj = obj.constructor === Array ? [] : {
    
    };
    for (let i in obj) {
    
    
      cloneObj[i] = typeof obj[i] === "object" ? deepCopy(obj[i]) : obj[i];
    }
  } else cloneObj = obj;
  return cloneObj;
}

猜你喜欢

转载自blog.csdn.net/weixin_43595755/article/details/118278763