深拷贝

78 阅读1分钟

手写简易深拷贝

const judgeType = obj => Object.prototype.toString.call(obj).split(' ')[1].split(']')[0]
const deepClone = obj => {
    if(!['Object', 'Null'].includes(judgeType(obj))) return obj
    let copy
    if(judgeType(obj) == 'Object') copy = {}
    if(judgeType(obj) == 'Array') copy = []
    for(let key in obj) {
        if(obj.hasOwnProperty(key))
            copy[key] = deepClone(obj[key])
    }
    return copy
}