手写一个简易的深拷贝

54 阅读1分钟
手写一个简易的深拷贝
  1. 技术要点:递归
  2. new obj.constructor() 相当于 Array.isArray(obj) ? [] : {}
  3. 加cache是为了防止循环引用
  4. for in 会走原型链,需要hasOwnProperty判断一下是否是自己的属性
//加cache是为了防止循环引用
function deepClone(obj,cache = new WeakMap()){
    if (typeof obj !== 'object' || obj == null){
        return obj
    }
    if (cache.has(obj)) return cache.get(obj)
    let result = new obj.constructor()
    cache.set(obj,result)
    for (let key in obj){
        if (obj.hasOwnProperty(key)){
            result[key] = deepClone(obj[key],cache)
        }
    }
    return result
}