应用场景: 赋值运算中 浅拷贝:指向的是堆内存中的同一个对象 深拷贝:指向堆内存中的不同的对象

1、浅拷贝

简单的赋值运算—浅拷贝

  1. var arr = [1,2,3,4]
  2. var newArr = arr
  3. newArr.push(5)
  4. console.log(arr);//1,2,3,4,5

2、深拷贝

赋值运算的时候只赋值,不赋址

  1. var arr1 = [1,2,3,4]
  2. var newArr1 = [...arr1]
  3. arr1.push(5)
  4. console.log(newArr1);//1,2,3,4
  5. var arr2 = [2,3,4,5]
  6. var newArr2 = arr2.slice(0,)
  7. arr2.push(6)
  8. console.log(newArr2);//2,3,4,5
  9. var newArr1 = [].concat(arr1)
  10. arr1.push(5)
  11. console.log(newArr1)
  12. var arr1 = [{name:'lisi'},{name:"wangwu"}]
  13. /* var newArr1 = [...arr1]
  14. arr1[0].name = 'react'
  15. console.log(newArr1); *///name:react
  16. var newArr1 = JSON.parse(JSON.stringify(arr1))
  17. arr1[0].name = 'react'
  18. console.log(newArr1);//name:"lisi"

Snipaste_2022-02-22_17-53-55.jpg