1. /**
  2. * 浅拷贝
  3. */
  4. const obj1 = {
  5. age: 20,
  6. name: 'xxx',
  7. address: {
  8. city: 'beijing'
  9. },
  10. arr:['a', 'b', 'c']
  11. }
  12. const obj2 = obj1
  13. obj2.address.city = "shanghai"
  14. console.log(obj1.address.city)

手写深拷贝

  • 注意判断值类型和引用类型
  • 注意判断数组还是对象
  • 递归(核心) ```javascript /**
    • 深拷贝 */

const obj1 = { age: 20, name: ‘xxx’, address: { city: ‘beijing’ }, arr:[‘a’, ‘b’, ‘c’] }

const obj2 = deepClone(obj1)

obj2.address.city = “shanghai” console.log(obj1.address.city)

/**

  1. * 深拷贝
  • @param obj 要拷贝的对象 */

function deepClone(obj = {}) { if (typeof obj !== ‘object’ || obj == null){ // obj 不是null或者不是对象和数组, 直接返回 return obj }

// 初始化返回结果 let result if (obj instanceof Array) { result = [] } else { result = {} }

for (let key in obj) { // 保证key不是原型的属性 if(obj.hasOwnProperty(key)){ // 递归 result[key] = deepClone(obj[key]) } } // 返回结果 return result }

``` https://zhuanlan.zhihu.com/p/80922071