手写一个深拷贝函数

对不同类型做不同的处理

// 深拷贝

function getType(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1);
}

function copyArray(ori, copy = []) {
  for (const [index, value] of ori.entries()) {
    copy[index] = deepCopy(value);
  }
  return copy;
}

function copyObject(ori, copy = {}) {
  for (const [key, value] of Object.entries(ori)) {

    copy[key] = deepCopy(value);
  }
  return copy;
}

function copyFunction(ori, copy = () => {}) {
  return eval('fn =' + ori.toString());
}

function deepCopy(ori){
  const type = getType(ori);
  let copy;
  switch(type) {
    case 'RegExp':
      return new RegExp(ori);
    case 'Date':
      return new Date(ori);
    case 'Array':
      return copyArray(ori, copy);
    case 'Function':
      return copyFunction(ori, copy);
    case 'Object':
      return copyObject(ori, copy);
    default:
      return ori;
  }
}
function test() {
  console.log(1);
}
let c = {
  a: [1,2,4],
  b: {
    a:1,
    b: {
      c:1
    }
  },
  e: /\.js/,
  f: function() {
    console.log(1);
  }
}

let res = deepCopy(c);
console.log(res.f === c.f)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。