一、简单数据类型

  1. 浅拷贝:newArr = arr
  2. // 简单的赋值
  3. var arr = [1,2,3,4];
  4. var newArr = arr;
  5. newArr.push(5)
  6. console.log(arr);//[1,2,3,4,5]
  1. 深拷贝:newArr
  2. <script>
  3. // 浅拷贝:指向的是堆内存的通风一个对象
  4. //深拷贝:指向堆内存的不同对象
  5. 1、扩展
  6. var arr = [1,2,3,4];
  7. var newArr = [...arr];
  8. newArr.push(5)
  9. console.log(arr);//[1,2,3,4]
  10. 2slice
  11. var arr = [1,2,3,4];
  12. var newArr = arr.slice(0,);
  13. arr.push(5)
  14. console.log(arr);//[1,2,3,4]
  15. 3concat
  16. var arr = [1,2,3,4]
  17. var newArr = [].concat(arr)
  18. newArr.push(5);
  19. console.log(arr);//[1,2,3,4]
  20. </script>

二、复杂数据类型

拷贝.png

  1. //浅拷贝
  2. <script>
  3. var arr = [{name:"lisi"},{name:"wangwu"}]
  4. var newArr = [...arr]
  5. arr[0].name = "react";
  6. console.log(arr);
  7. </script>

JSON.parse JSON.stringify实现

  1. //深拷贝 JSON.parse JSON.stringify
  2. <script>
  3. var arr = [{name:"lisi"},{name:"wangwu"}];
  4. var newArr = JSON.parse(JSON.stringify(arr));
  5. arr[0].name = "react"
  6. console.log(newArr);
  7. </script>

算法实现

  1. <script>
  2. var arr = [{name:"lisi"},{name:"wangwu"}];
  3. function deepClone(obj){
  4. //如果是初始值 直接返回
  5. let result;
  6. if(obj instanceof Array){
  7. result = []
  8. }else if(typeof obj =="object"){
  9. result = {}
  10. }else{
  11. return obj
  12. }
  13. for(let key in obj){
  14. result[key] = deepClone(obj[key])
  15. }
  16. return result
  17. }
  18. var newArr = deepClone(arr)
  19. arr[0].name = "react"
  20. console.log(newArr);
  21. </script>