JS实现深拷贝

291 阅读1分钟

常用的实现深拷贝的方法:

1、使用JSON.stringify
const arr = [
	{ a: new Date(), aa: new RegExp('\\w+'), aaa: function() { console.log('aaa function') } }, 
	{ b: 'qwe' }, 
	{ c: [null, undefined] }, 
	{ d: [{ da: 1, db: { dba: 123 }}] }
]
const copyArr = JSON.parse(JSON.stringify(arr))
console.log(copyArr)

不足: 1、日期类型的数据会直接变成字符串的形式,而不是对象的形式

2、正则类型的数据会变成空对象{}

3、函数会丢失

优点:能够满足大部分的业务需求、代码量少

2、自定义实现深拷贝函数

相比较于JSON.stringify的方式增加了日期和正则类型的数据的拷贝

function clone(obj) {
  // 当null NaN undefined number string等基本数据类型时直接返回
  if (obj === null || typeof obj !== 'object') {
    return obj
  }
  // Date类型
  if (obj instanceof Date) {
    const copy = new Date()
    copy.setTime(obj.getTime())
    return copy
  }
  // 正则类型类型
  if (obj instanceof RegExp) {
    const Constructor = obj.constructor
    return new Constructor(obj)
  }
  // 如果是数组等引用数据类型
  if (obj instanceof Array || obj instanceof Object) {
    const copyObj = Array.isArray(obj) ? [] : {}
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        copyObj[key] = clone(obj[key])
      }
    }
    return copyObj
  }
}

不足:没有实现函数的复制