js深拷贝

j

需要注意的是JS中,数组  instanceof Object为true

let oldObj = {
    a:[1,2,3],
    b:null,
    c:undefined,
    d:{
        a:1
    }
}
let newObj = {}
function deepCopy(newObj,oldObj) {
    for (let key in oldObj){
        let item = oldObj[key]
        //注意此处要先判断Array,因为数组instanceof Object也为true
        if(item instanceof Array){
            newObj[key]=[]
            deepCopy(newObj[key],item)
        }else if(item instanceof Object){
            newObj[key]={}
            deepCopy(newObj[key],item)
        }else{
            newObj[key] = item
        }
    }
}
deepCopy(newObj,oldObj)
console.log(newObj)

 

About the author

wangxin

Add Comment