js实现深度拷贝

function deepCopy(obj) {
    if(!obj || typeof obj != 'object'){
        return null
    }
    const targetObj = Array.isArray(obj)? [] : {}
    for(let key in obj){
        if(obj.hasOwnProperty(key)){
            if(obj[key] && typeof obj[key]=== 'object'){
                targetObj[key] = deepCopy(obj[key])
            } else {
                targetObj[key] = obj[key]
            }
        }
    }
    return targetObj;
}

    let person = {
        name: 'gxr',
        age: 22,
        friend: {
            janiffer: {
                age: 34,
                address: 'hangzhou'
            },
            john: {
                age: 24,
                address: 'beijing'
            }
        }
    }

    let people = deepCopy(person);

    console.log(person === people ? true : false)

    people.name = 'geo'

    console.log(people)
    console.log(person)

 

posted @ 2018-08-21 11:32  gaoxuerong  阅读(449)  评论(0编辑  收藏  举报