zoukankan      html  css  js  c++  java
  • 重温js浅拷贝、深拷贝

    假如我们现在需要拷贝一个对象:obj到目标对象obj2中,我们可以这样做:

    浅拷贝

    obj2 = Object.assign({}, obj)
    // 或者
    obj2 = {...obj}
    

    深拷贝

    为何要深拷贝我就不多bb了

    方法一:

    
    JSON.parse(JSON.stringify(obj))
    
    

    优点:绝大部分场景够用,性能最佳、写起来爽

    缺点:会忽略 undefined、Symbol、BigInt 、函数

    方法二:使用loadsh的cloneDeep

    方法三:自己手写一个

      function deepClone(obj, newObj){
        let typeArr = ['[object Function]', '[object RegExp]', '[object Date]']; // 这里可以根据实际情况自己加呀
        let  toStr = '';
        for(let i in obj){
          if(obj[i] == null || typeof obj[i] != 'object'){
            newObj[i] = obj[i]
          }else{ // 为什么这里不用else if,主要是为了少执行一点 Object.prototype.toString.call(obj[i])
            toStr = Object.prototype.toString.call(obj[i]);
            if(typeArr.includes(toStr)){
              newObj[i] = obj[i]
            }else {
              newObj[i] = Array.isArray(obj[i]) ? [] : {}
              deepClone(obj[i], newObj[i])
            }
          }
        }
      }
    
    • 示例
      var obj1 = {
        a: 11,
        b: [1,2,{a:1}],
        c: {
          a:1,
          b: {
            a:1,
            b:2
          }
        },
        d: null,
        e: undefined,
        f: new Date(),
        g: function(){},
      }
      var obj2 = {}
      deepClone(obj1,obj2)
      obj1.c.b.a=2;
      console.log("obj2",obj2)
    
    青云直上三千码
  • 相关阅读:

    二分查找法
    LeetCode-Two Sum III
    LeetCode-Add and Search Word
    LeetCode-Longest Substring with At Least K Repeating Characters
    LeetCode-Rearrange String k Distance Apart
    LeetCode-Game of Life
    LeetCode-Walls and Gates
    LeetCode-Water and Jug Problem
    LeetCode-Inorder Successor in BST
  • 原文地址:https://www.cnblogs.com/djjlovedjj/p/14594893.html
Copyright © 2011-2022 走看看