美文网首页JavaScript
浅拷贝与深拷贝

浅拷贝与深拷贝

作者: 开着五菱宏光的小白 | 来源:发表于2020-05-15 10:53 被阅读0次

    浅拷贝

    浅拷贝只拷贝一层,深层次的对象只拷贝引用

    var obj = {
        name: 'zhangsan',
        age: 18,
        omg: {
            name: 'omg'
        }
    }
    
    var ob = {};
    for (var i in obj) {
        ob[i] = obj[i]
    }
    
    console.log(ob);
    
    
    拷贝对象ob

    ob深层对象omg改变会改变原始对象obj中的omg

    var obj = {
        name: 'zhangsan',
        age: 18,
        omg: {
            name: 'omg'
        }
    }
    
    var ob = {};
    for (var i in obj) {
        ob[i] = obj[i]
    }
    ob.omg.name = 'ob';
    ob.name = 'omg';
    console.log(ob)
    console.log(obj);
    
    浅拷贝会改变深层对象

    ES6 新增的浅拷贝方法 Object.assign

    var obj = {
        name: 'zhangsan',
        age: 18,
        omg: {
            name: 'omg'
        }
    }
    
    var ob = {};
    Object.assign(ob,obj);
    
    console.log(ob)
    
    对象浅拷贝方法assign

    利用递归进行对象的深拷贝

    var obj = {
        name: 'zhangsan',
        age: 18,
        omg: {
            name: 'omg'
        },
        yy: [1,2,3]
    }
    
    var ob = {};
    function deepCopy(newO,oldO) {
        for (var k in oldO) {
            var item = oldO[k];
            if (item instanceof Array) {
                newO[k] = [];
                deepCopy(newO[k],item);
            } else if (item instanceof Object) {
                newO[k] = {};
                deepCopy(newO[k],item);
            } else {
                newO[k] = item;
            }
        }
    }
    
    deepCopy(ob,obj);
    ob.omg.name = 'ccc';
    ob.yy.push(1,2);
    console.log(ob);
    console.log(obj);
    
    深拷贝

    相关文章

      网友评论

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

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