变量存储类型

  • 基本类型:直接存储在栈中的数据。(string、boolean、undefined、number、null)
  • 引用类型:将该对象引用地址存储在栈中,然后对象里面的数据存放在堆中。(Array、Object、Function)

浅拷贝

浅拷贝就是指对象复制的时候只复制一层

如何浅拷贝

  1. const person = {
  2. name: '长青',
  3. intoduce: () => {
  4. console.log('你好! 我是长青。')
  5. }
  6. }
  7. // 方法一
  8. const chagnqing1 = Object.assign({}, person)
  9. // 方法二
  10. const chagnqing2 = {...person}

手写浅拷贝

  1. const shallowClone = (target) => {
  2. if (target && typeof target === 'object') {
  3. const temp = Array.isArray(target) ? [] : {}
  4. for (let key in target) {
  5. temp[key] = target[key]
  6. }
  7. return temp
  8. }
  9. return target
  10. }

深拷贝

深拷贝是指复制对象的所有层级

如何深拷贝

  1. const person = {
  2. name: '长青',
  3. info:{},
  4. intoduce: () => {
  5. console.log('你好! 我是长青。')
  6. }
  7. }
  8. // =====================方法一==================================
  9. // 乞丐版(JSON.stringify)会存在属性丢失
  10. let cq = JSON.parse(JSON.stringify(person))
  11. // =====================方法二==================================
  12. // 使用递归进行深拷贝
  13. const deepClone = (target, hash = new WeakMap()) => {
  14. if (target.constructor === Date)
  15. return new Date(target) // 日期对象直接返回一个新的日期对象
  16. if (target.constructor === RegExp)
  17. return new RegExp(target)
  18. // 引入 hash 解决循环引用
  19. if (hash.has(target)) return hash.get(target)
  20. hash.set(target, target)
  21. if (target && typeof target === 'object') {
  22. const temp = Array.isArray(target) ? [] : {}
  23. for (let key in target) {
  24. if (typeof target[key] === 'object') {
  25. temp[key] = deepClone(target[key], hash)
  26. } else {
  27. temp[key] = target[key]
  28. }
  29. }
  30. return temp
  31. }
  32. return target
  33. }
  34. const lmm = deepClone(person)
  35. lmm.name = '林妹妹'
  36. lmm.info.gender = false
  37. console.log(lmm);
  38. console.log(person);