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

34次阅读

共计 441 个字符,预计需要花费 2 分钟才能阅读完成。

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
}

正文完
 0