关于前端没有人不会的深拷贝

60 阅读1分钟

深拷贝, 不难,注意循环引用即可

const map = new Map()
const deepClone = obj => {
  const res = obj.constructor === Array ? [] : {}

  map.set(obj, res) // 这里是res 而不是 obj

  for (const key in obj) {
    if (Object.hasOwnProperty.call(obj, key)) {
      const element = obj[key];
      const type = Object.prototype.toString.call(element)
      // 复杂类型 
      if (type === '[object Array]' || type === '[object Object]') {
        // 从map中取
        if (map.has(element)) {
          res[key] = map.get(element)
        } else {
          res[key] = deepClone(element)
        }
      } else {
        res[key] = element
      }
    }
  }


  return res
}