美文网首页
js 浅拷贝和深拷贝

js 浅拷贝和深拷贝

作者: 丹丹_ccd5 | 来源:发表于2019-03-06 18:14 被阅读0次
    堆和栈

    栈(stack)为自动分配内存空间,它由系统自动释放。堆(heap)则是动态分配内存,大小不定也不会自动释放

    数据类型
    • 基本数据类型:Boolean, String, Number, undefined, null, Symbol
      保存在栈中
    • 引用类型:Object
      数据保存在堆中, 指针保存在栈中
    浅拷贝

    对象只会被克隆最外部的一层,对于子对象,依然通过引用指向同一块堆内存

    • Object.assign方式 Object.assign(target, source1, source2)
    • for...in...
    function shallowClone (obj) {
      const cloneObj = {}
      for (let i in obj) {
        cloneObj[i] = obj[i]
      }
      return cloneObj
    }
    
    深拷贝
    • JSON.parse(JSON.stringify(obj))


      JSON.parse(JSON.stringify(obj)拷贝

      我们可以看到,obj和arr正常拷贝,但是date变成了字符串,reg变成了空对象,fun直接不见了。所以该方法只能拷贝一些简单的对象,不适合复杂对象的拷贝。

    • for...in...加递归
    const isObj = (obj) => (typeof obj === 'object' || typeof obj === 'function') && obj !== null
    function deepClone(obj) {
      const tempObj = Array.isArray(obj) ? [] : {}
      for (let i in obj) {
        tempObj[i] = isObj(obj[i]) ? deepClone(obj[i]) : obj[i]
      }
      return tempObj
    }
    
    

    拷贝的结果是:


    for..in加递归拷贝的结果

    我们看到此时date、fun、reg都变成了空对象


    • 环就是对象循环引用,导致自己成为一个闭环
      如:
      闭环
      对闭环进行拷贝时报错:
      爆栈
      可以使用WeakMap结构存储被保存的对象,每一次被拷贝时就先向WeakMap查询。
    function deepClone(obj, map = new WeakMap()) {
      if (map.has(obj)) {
        return has.get(obj)
      }
      const tempObj = Array.isArray(obj) ? [] : {}
      map.set(obj, tempObj)
      for (let i in obj) {
        tempObj[i] = isObj(obj[i]) ? deepClone(obj[i]) : obj[i]
      }
      return tempObj
    }
    
    • 结合以上,解决Date、RegExp、Function的深拷贝如下
    function deepClone (obj, map = new WeakMap()) {
      let cloneObj
      let Constructor = obj.constructor
      switch (Constructor) {
        case Date:
          cloneObj = new Constructor(obj.getTime())
          break
        case RegExp:
          cloneObj = new Constructor(obj)
          break
        case Function:
          cloneObj = function () {
            const temp = function temporary() { return this.apply(obj, arguments) }
            for( let key in obj ) {
              if (obj.hasOwnProperty(key)) {
                temp[key] = obj[key]
              }
            }
            return temp
          }
          break
        default:
          if (map.has(obj)) {
            return map.get(obj)
          }
          cloneObj = new Constructor()
          map.set(obj, cloneObj)
          break;
      }
      for (const key in obj) {
        cloneObj[key] = isObj[obj[key]] ? deepClone(obj[key]) : obj[key]
      }
      return cloneObj
    }
    
    拷贝结果

    相关文章

      网友评论

          本文标题:js 浅拷贝和深拷贝

          本文链接:https://www.haomeiwen.com/subject/kjsxuqtx.html