先来搞清楚概念

浅拷贝:

浅.png

创建一个新对象,这个对象有着原始对象属性值的一份精确拷贝。如果属性是基本类型,拷贝的就是基本类型的值,如果属性是引用类型,拷贝的就是内存地址 ,所以如果其中一个对象改变了这个地址,就会影响到另一个对象。

深拷贝:

sheng.png

将一个对象从内存中完整的拷贝一份出来,从堆内存中开辟一个新的区域存放新对象,且修改新对象不会影响原对象


无废话,直接上代码

浅拷贝:

  1. // 引用类型的浅拷贝
  2. const obj1 = {
  3. age: 20,
  4. name: "xxx",
  5. address: {
  6. city: "beijing"
  7. },
  8. arr: ["a", "b", "c"]
  9. };
  10. const obj2 = obj1;
  11. obj2.address.city = "上海";
  12. console.log(obj1.address.city); //上海

深拷贝:

  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 = deepClone(obj1);
  13. obj2.address.city = "shanghai";
  14. obj2.arr[0] = "a1";
  15. console.log(obj1.address.city); //beijing
  16. console.log(obj2.address.city); //shanghai
  17. console.log(obj1.arr[0]); //a
  18. /**
  19. * 深拷贝
  20. * @param {Object} obj 要拷贝的对象
  21. */
  22. function deepClone(obj = {}) {
  23. if (typeof obj !== "object" || obj == null) {
  24. // obj 是 null ,或者不是对象和数组,直接返回
  25. return obj;
  26. }
  27. // 初始化返回结果
  28. let result;
  29. if (obj instanceof Array) {
  30. result = [];
  31. } else {
  32. result = {};
  33. }
  34. for (let key in obj) {
  35. // 保证 key 不是原型的属性
  36. if (obj.hasOwnProperty(key)) {
  37. // 递归调用!!!
  38. result[key] = deepClone(obj[key]);
  39. }
  40. }
  41. // 返回结果
  42. return result;
  43. }