使用扩展运算符实现数组,对象的深拷贝

1.数组深拷贝

 var array = [{name: 'jack'}, 2, 3]  
    var newArr = array
    var copyArr = [...array] 
    array.push({
      age: 18
    })
    console.log(array, 'array') //changed
    console.log(newArr, 'newArr') // changed
    console.log(copyArr, 'copyArr') // keep origin array

2.对象深拷贝

    var obj = {
      name: 'gaby'
    }
    var newObj = obj
    var copyObj = {...obj}
    obj.gender = 'female'
    console.log(obj, 'obj') //changed 
    console.log(newObj, 'newObj') // changed
    console.log(copyObj, 'copyObj')  //keep origin obj

 

posted on 2021-09-01 09:09  荻!!!!!!!!  阅读(84)  评论(0编辑  收藏  举报