乐趣区

关于javascript:用递归写的深度复制

function cloneDeep(old) {let map = new WeakMap()
    return cloneDeepCon(old, map)
}
function cloneDeepCon(old, map) {if (!(old && typeof old === 'object')) return old

    let existObj = map.get(old)
    if (existObj) return existObj

    let oldClone = Array.isArray(old) ? [] : {}

    map.set(old, oldClone)

    let keys = Object.getOwnPropertyNames(old)

    keys.forEach((key) => {oldClone[key] = cloneDeepCon(old[key], map) 
        Object.defineProperty(
            oldClone,
            key,
            Object.getOwnPropertyDescriptor(old, key)
        )
    })

    return oldClone
}
退出移动版