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

    

  • 相关阅读:
    利用dockerfile定制镜像
    发布Docker 镜像到dockerhub
    Docker 停止容器
    133. Clone Graph
    132. Palindrome Partitioning II
    131. Palindrome Partitioning
    130. Surrounded Regions
    129. Sum Root to Leaf Numbers
    128. Longest Consecutive Sequence
    127. Word Ladder
  • 原文地址:https://www.cnblogs.com/ljwk/p/11065237.html
Copyright © 2011-2022 走看看