【JavaScript】深浅拷贝

115 阅读1分钟

项目中遇到的问题

  const groupList = [{
    name: 'lilei',
    age: '24'
  }]

  const echoList = groupList

  groupList.map(item => {
    item.name = 'hanmeimei'
  })

  console.log(echoList)  // [{name: 'hanmeimei', age: '24'}]
  

浅拷贝是拷贝引用,拷贝后的引用都指向同一个存放数据位置的指针。B复制了A,A修改时,B也跟着变了,这是浅拷贝,B没变,就是深拷贝

实现深拷贝

  1. JSON.parse 实现
  const echoList = JSON.parse(JSON.stringify(groupList))
  console.log(echoList)  // [{name: 'lilei', age: '24'}]
  1. 递归实现
  function deepClone(context) {
    let result
    // 传入的参数是基本数据类型时,直接赋值复制
    if (context && typeof context !== 'object') {
      result = context
    } else if (context && typeof context === 'object') {
      // 判断传入的参数是数组还是对象
      result = Array.isArray(context) ? [] : {}

      // 遍历context
      for (let key in context) {
        if (context.hasOwnProperty(key)) {
          // 若元素类型为对象,则递归调用该方法
          if (context[key] && typeof context[key] === 'object') {
            result[key] = deepClone(context[key])
          } else {
            result[key] = context[key]
          }
        }
      }
    }
    return result
  }

  const echoList = deepClone(groupList)