深拷贝

121 阅读1分钟
  1. JSON.stringify 的问题
// ..........JSON.stringify 的确点............

// 1. 会忽略值为 undefined、函数、Symbol
// 2. 当值为 bigint 或循环引用的时候会报错
// 3. 日期会被转成字符串、正则会被转成空对象
// 4. ...
  1. 三个点和 Object.assign 都是浅拷贝
它们都是用来进行浅拷贝的,好的地方是能拷贝 undefined、函数、Symbol、正则...
  1. 自己实现深拷贝:递归浅拷贝
const copy = (target) => {
  const type = Object.prototype.toString.call(target)
  // 正则、日期
  if (/(regexp|date)/i.test(type)) return new target.constructor(target)
  // 错误对象
  if (/error/i.test(type)) return new target.constructor(target.message)
  // 函数
  if (/function/i.test(type)) return new Function('return ' + target.toString())()
  // null 和 简单数据类型
  if (target === null || typeof target !== 'object') return target
  // 数组和对象
  /* const arr = []
  const obj = {} */
  const result = new target.constructor()
  for (const attr in target) {
    result[attr] = copy(target[attr])
  }
  return result
}
  1. 如何循环引用
const copy = (target, m = new Map()) => {
  const type = Object.prototype.toString.call(target)
  // 正则、日期
  if (/(regexp|date)/i.test(type)) return new target.constructor(target)
  // 错误对象
  if (/error/i.test(type)) return new target.constructor(target.message)
  // 函数
  if (/function/i.test(type)) return new Function('return ' + target.toString())()
  // null 和 简单数据类型
  if (target === null || typeof target !== 'object') return target
  // 数组和对象
  /* const arr = []
  const obj = {} */
  // #2 m 里面存储了 target 就直接返回
  // console.log(target, 233)

  if (m.get(target)) return m.get(target)
  const result = new target.constructor()
  // #3
  m.set(target, result)

  for (const attr in target) {
    // #4 传递 m
    result[attr] = copy(target[attr], m)
  }
  return result
};
  1. 实际我怎么做的
const o = _.cloneDeep(obj1)