深拷贝手写

时间:2022-07-26
本文章向大家介绍深拷贝手写,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
function deepClone(obj = {}) {
    if (typeof obj !== 'object' || obj == null) {
        return obj;
    }
    
    let result
    if (obj instanceof Array) {
        result = []
    } else {
        result = {}
    }
    
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            result[key] = deepClone(obj[key])
        }
    }
    
    return result
}