手写算法-深拷贝(完整版)

 ts版本:

const deepClone = (obj: any) => {
  if (typeof obj !== 'object' || obj === null) {
    return obj
  }

  let copy: any

  if (obj instanceof Date) {
    copy = new Date(obj)
  } else if (obj instanceof RegExp) {
    copy = new RegExp(obj)
  } else if (obj instanceof Function) {
    copy = function () {
      // eslint-disable-next-line prefer-rest-params
      return obj.apply(this, arguments)
    }
  } else if (typeof obj === 'symbol') {
    copy = Object(Symbol.prototype.valueOf.call(obj))
  } else if (Array.isArray(obj)) {
    copy = []
    for (let i = 0; i < obj.length; i++) {
      copy[i] = deepClone(obj[i])
    }
  } else {
    copy = {}
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        copy[key] = deepClone(obj[key])
      }
    }
  }

  return copy
}

js版本:

function deepClone(obj) {
  if (typeof obj !== 'object' || obj === null) {
    return obj
  }

  let copy

  if (obj instanceof Date) {
    copy = new Date(obj)
  } else if (obj instanceof RegExp) {
    copy = new RegExp(obj)
  } else if (obj instanceof Function) {
    copy = function () {
      return obj.apply(this, arguments)
    }
  } else if (obj instanceof Symbol) {
    copy = Object(Symbol.prototype.valueOf.call(obj))
  } else if (obj instanceof Array) {
    copy = []
    for (let i = 0; i < obj.length; i++) {
      copy[i] = deepClone(obj[i])
    }
  } else {
    copy = {}
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        copy[key] = deepClone(obj[key])
      }
    }
  }

  return copy
}

以下给出实例验证:

// 定义一个复杂对象
const complexObj = {
  name: 'Alice',
  date: new Date(),
  regex: /abc/g,
  func: function() {
    console.log('Hello!');
  },
  arr: [1, 2, 3],
  symbol: Symbol('foo')
};

// 执行深拷贝
const copiedObj = deepClone(complexObj);

// 修改对象属性
copiedObj.name = 'Bob';
copiedObj.date.setDate(10);
copiedObj.regex = /def/i;
copiedObj.func = function() {
  console.log('Hi!');
};
copiedObj.arr.push(4);
copiedObj.symbol = Symbol('bar');

// 对比原始对象和修改后的对象
console.log('Original Object:', complexObj);
console.log('Modified Object:', copiedObj);

打印结果如下:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值