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

浅拷贝和深拷贝

作者: 江湖小盛 | 来源:发表于2022-10-11 16:52 被阅读0次

    对象浅拷贝

    1、 Object.assign()

    var obj = {
          name: 'zhang',
          info: {
            age: 10,
          },
          grade: [10, 20]
        }
    var copyObj = Object.assign({}, obj)
    

    2、es6 展开运算符...

    var obj = {
          name: 'zhang',
          info: {
            age: 10,
          },
          grade: [10, 20]
        }
    var copyObj =  { ... obj }
    

    数组浅拷贝

    1、Array.slice() 数组截取,返回新的数组

    var arr = [10, {age: 1, info: {name: 'zhangsan'}}]
    var copyArr = arr.slice()
    

    2、Array.concat() 数组合并

    var arr = [10, {age: 1, info: {name: 'zhangsan'}}]
    var copyArr = arr.concat([], arr)
    

    3、es6 展开运算符...

    var arr = [10, {age: 1, info: {name: 'zhangsan'}}]
    var copyArr = [...arr]
    

    递归实现对象深拷贝

    拷贝的时候判断一下属性值的类型,如果是对象,我们递归调用深拷贝函数
    var obj = {
      name: 'zhang',
      info: {
        age: 10,
      },
      grade: [10, 20]
    }
    
    var deepCopy = function(obj) {
        if (typeof obj !== 'object') return;
        var newObj = obj instanceof Array ? [] : {};
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
            }
        }
        return newObj;
    }
    

    相关文章

      网友评论

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

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