Skip to content

手写深拷贝

将一个对象深拷贝到一个新的对象中,新对象和原对象不共享内存。

代码展示
js
// 深拷贝
const deepClone = (obj, map = new WeakMap()) => {
    if (obj !== null || typeof obj !== 'object') return obj
    if (map.has(obj)) {
        return map.get(obj)
    }
    let res = Array.isArray(res) ? [] : {}
    map.set(obj, res)
    for (key in obj) {
        if (obj.hasOwnProperty(item)) {
            res[key] = deepClone(obj[key], map)
        }
    }
    return res
}