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);
    

    

  • 相关阅读:
    hdu5714 拍照[2016百度之星复赛C题]
    hdu5715 XOR 游戏 [2016百度之星复赛D题]
    AFO
    BZOJ 3566 概率充电器
    BZOJ 3427 Bytecomputer
    BZOJ 4513 储能表
    BZOJ 3667 Miller_Rabin
    BZOJ 4557 侦察守卫
    BZOJ 3894 文理分科
    SUOI #69 奔跑的Aqua
  • 原文地址:https://www.cnblogs.com/ljwk/p/11065237.html
Copyright © 2011-2022 走看看