zoukankan      html  css  js  c++  java
  • js对象的浅拷贝与深拷贝

    // 浅拷贝
    const shallow = {a: 1};
    const new11 = shallow;
    const new22 = {};
    Object.assign(new22, shallow);
    
    // 深拷贝
    function deepClone(obj) {
        if (obj === null || typeof obj !== 'object') return obj;
        var result = Array.isArray(obj) ? [] : {};
    
        // 拷贝Symbols
        const sym = Object.getOwnPropertySymbols(obj);
        sym.forEach(function (item) {
            if (Object.prototype.toString.call(obj[item]) === '[object Object]') {
                result[item] = deepClone(obj[item]);
            } else {
                result[item] = obj[item];
            }
        });
    
        // 拷贝其他值
        for (var key in obj) {
            if (Object.prototype.toString.call(obj[key]) === '[object Object]') {
                result[key] = deepClone(obj[key]);
            } else {
                result[key] = obj[key];
            }
        }
    
        return result;
    }
    
    const complexObj = {
        a: 'string',
        b: 0,
        c: true,
        d: null,
        e: undefined,
        f: Symbol(),
        g: {
            aa: 'test',
            bb: function() {
                console.log('inner');
            }
        },
        h: function() {
            console.log('outer');
        },
        i: [1, 2, 3, 4, 5]
    };
    const new1 = JSON.parse(JSON.stringify(complexObj)); // JSON方法的深拷贝,有缺陷
    const new2 = deepClone(complexObj);
    // 修改数据
    complexObj.b = 123; // 第一层
    complexObj.g.aa = 'abc'; // 对象第二层
    console.log(complexObj);
    console.log(new1);
    console.log(new2);
    

    

  • 相关阅读:
    指针细说
    C++编码规范101
    关于C标准
    Bjarne Stroustrup语录2
    Bjarne Stroustrup 语录1
    计算机网络基础识别
    ssh
    matplotlib画图
    数据分析之Numpy
    数据分析
  • 原文地址:https://www.cnblogs.com/ljwk/p/11065237.html
Copyright © 2011-2022 走看看