记录对象深拷贝的两中方法

对象深拷贝,两种方法,各种骚操作准备开始了喔…

// 方法一:最简单的操作
/**
 * 此种方法克隆
 * obj不能为Function RegExp Date ...
 */
export function deepCopy(obj) {
     
    return JSON.parse(JSON.stringify(obj))
}

// 方法二:交完整的操作(根据情况进行使用)
/**
 * 深克隆对象,数组
 * new WeakMap() 功能和new Map()一样,但key必须是对象,也是弱链接,内存可以释放
 * hash值主要排除 let obj={} obj.a=obj 这种克隆 deepClone(obj)
 * for in 可以遍历对象和数组而且会遍历原型,需要加上hasOwnProperty过滤
 * zg 2020.5.26
 */
export function deepClone(obj, hash = new WeakMap()) {
     
    // 排除常见异常
    if (obj == null) return obj
    if (obj instanceof RegExp) return new RegExp(obj)
    if (obj instanceof Date) return new Date(obj)
    if (typeof obj !== 'object') return obj
    // 如果之前拷贝过,就把拷贝后的结果返回
    if (hash.has(obj)) return hash.get(obj)
    // 剩下对象和数组
    const instance = new obj.constructor()
    // 把当前拷贝的和拷贝后的做一个映射
    hash.set(obj, instance)
    // 遍历对象或者数组
    // eslint-disable-next-line no-restricted-syntax
    for (const key in obj) {
     
        // eslint-disable-next-line no-prototype-builtins
        if (obj.hasOwnProperty(key)) {
     
            instance[key] = deepClone(obj[key], hash)
        }
    }
    return instance
}

你可能感兴趣的:(JS学习)