实现浅拷贝和深拷贝

117 阅读1分钟
    let obj={
        a:'哈哈',
        b:12,
        c:['12','z','c'],
        dog:{
          name:'二狗',
          age:4
        }
    }
实现浅拷贝
  function copy(obj){
    let newObj={}
    for(var key in obj){
    newObj[key]=obj[key]
    }
    return newObj 
}
console.log(copy(obj))
实现深拷贝
  function deepClone(obj){
    let newObj
    if(typeof(obj)!=='object'|| obj===null){
        return obj
    }
    if(obj instanceof Array){
        newObj=[]
    } else{
        newObj={}
    }
    for(let key in obj){
        newObj[key]=deepClone(obj[key])
    }
    return newObj
    }
    let a=deepClone(obj)
    a.dog.age=666
    console.log(a)
    console.log(obj)