浅拷贝的几种方法[浅拷贝不能深层次拷贝]

  1. let hd = {
  2. name: '你好啊',
  3. year: 12312
  4. }
  5. // 浅拷贝的几种方法
  6. let obj = { ...hd }
  7. obj.name = '132'
  8. console.log(obj);//{name: '132', year: 12312}
  9. console.log(hd);//{name: '你好啊', year: 12312}
  10. 方法2
  11. let obj = Object.assign({}, hd)
  12. obj.name = 'hello'
  13. console.log(obj);//{name: 'hello', year: 12312}
  14. console.log(hd);//{name: '你好啊', year: 12312}

深拷贝

  1. 案例1
  2. let hd = {
  3. name: 'hello',
  4. year: 999,
  5. user: {
  6. name: "word"
  7. }
  8. }
  9. function copy(object) {
  10. let res = {}
  11. for (const key in object) {
  12. res[key] = typeof object[key] == 'object' ? copy(object[key]) : object[key]
  13. }
  14. return res
  15. }
  16. let data = copy(hd)
  17. data.user.name = 'hello word'
  18. console.log(JSON.stringify(data, null, 2));
  19. console.log(JSON.stringify(hd, null, 2));
  20. /*
  21. {
  22. "name": "hello",
  23. "year": 999,
  24. "user": {
  25. "name": "hello word"
  26. }
  27. }
  28. index.html:34 {
  29. "name": "hello",
  30. "year": 999,
  31. "user": {
  32. "name": "word"
  33. }
  34. }
  35. */
  36. 案例2
  37. let hd = {
  38. name: 'hello',
  39. year: 999,
  40. user: {
  41. name: "word"
  42. },
  43. arr: [123, 456]
  44. }
  45. function copy(object) {
  46. let res = object instanceof Array ? [] : {}
  47. for (const [k,v] of Object.entries(object)) {
  48. res[k] = typeof v== 'object' ? copy(v) : v
  49. }
  50. return res
  51. }
  52. let data = copy(hd)
  53. data.arr.push(789)
  54. console.log(JSON.stringify(data, null, 2));
  55. console.log(JSON.stringify(hd, null, 2));
  56. /*
  57. {
  58. "name": "hello",
  59. "year": 999,
  60. "user": {
  61. "name": "word"
  62. },
  63. "arr": [
  64. 123,
  65. 456,
  66. 789
  67. ]
  68. }
  69. index.html:54 {
  70. "name": "hello",
  71. "year": 999,
  72. "user": {
  73. "name": "word"
  74. },
  75. "arr": [
  76. 123,
  77. 456
  78. ]
  79. }
  80. */