Skip to content

深拷贝

js
const oldObj = {
        name: 'lzw',
        age: 18,
        array: [1,2,3],
        friend: {
            name: '张三',
            age: 20
        }
    }

    function deepClone(obj, map = new WeakMap()) {
        if(typeof obj !== 'object' || obj ===null) {
            return obj
        }

        if(map.has(obj)) {
            return map.get(obj)
        }
        
        let result;

        if(obj instanceof Array) {
            result = [];
        } else {
            result = {}
        }

        map.set(obj, result)

        for(let key in obj) {
            if(obj.hasOwnProperty(key)) {
                result[key] = deepClone(obj[key])  
            }
        }

        return result;
    }

    const newobject = deepClone(oldObj)
    newobject.name = '张三'
    newobject.friend.name = '李四'
    newobject.age = 12;
    console.log('oldObj', oldObj)
    console.log('newobject', newobject)