javascript 深拷贝写法

828 阅读1分钟

拷贝目标:target, 新对象:newObj

第一种写法:

JSON.parse(JSON.stringify(target))

这种写法比较简单轻便,但是拷贝目标必须遵从JSON的格式,当遇到层级较深,且序列化对象不完全符合JSON格式时,该方法就有些不妥。

let target = {
  a: '1',
  b: '2',
  c: function func() {
    console.log('copy test')
  }
}
let newObj = JSON.parse(JSON.stringify(target))
// newObj: {a: "1", b: "2"}

但是,目前在项目不少部分,我都有使用该方法。


第二种写法:

// 深拷贝函数
function deepCopy (target) {
  let result
  if (target !== null && typeof target === 'object') {
    try {
      if (Array.isArray(target)) {
        result = []
        for (let key = 0; key < target.length; key++) {
          result[key] = deepCopy(target[key])
        }
      } else {
        result = {}
        for (let key in target) {
          result[key] = deepCopy(target[key])
        }
      }
    } catch (e) {
      return result
    }
  } else {
    result = target
  }
  return result
}

这种写法能够避免第一种方法的一些问题。

请大家多多指教