js对象深拷贝、浅拷贝

浅拷贝1
//浅拷贝1
let obj01 = {
    name: 'Lily',
    age: '20',
    time: ['13', '15'],
    person: {
        name: 'Henry',
        age: '21'
    }
};
let obj02 = obj01;
obj02.age = '25'; //会改变obj11的age
obj02.person.age = '25'; //会改变obj11的person.age
obj02.time[1] = '25'; //会改变obj11的time值
console.log(obj01);

浅拷贝2-只复制一层对象的属性,如果对象中的属性值是对象,浅拷贝并不会复制对象属性中的属性

//浅拷贝2-只复制一层对象的属性,如果对象中的属性值是对象,浅拷贝并不会复制对象属性中的属性
let obj11 = {
    name: 'Lily',
    age: '20',
    time: ['13', '15'],
    person: {
        name: 'Henry',
        age: '21'
    }
};
let obj12 = {
    age: '22'
};
let obj13 = Object.assign({}, obj11, obj12);
obj13.age = '25'; //不会改变obj11的age
obj13.person.age = '25'; //会改变obj11的person.age
obj13.time[1] = '25'; //会改变obj11的time值
浅拷贝3-三点(...)
//浅拷贝1
let obj01 = {
    name: 'Lily',
    age: '20',
    time: ['13', '15'],
    person: {
        name: 'Henry',
        age: '21'
    }
};
let obj02 = {...obj01};
obj02.age = '25'; //会改变obj11的age
obj02.person.age = '25'; //会改变obj11的person.age
obj02.time[1] = '25'; //会改变obj11的time值
console.log(obj01);

深拷贝方法1-JSON.parse(JSON.stringify(obj))
//深拷贝方法1-JSON.parse(JSON.stringify(obj))
let obj21 = {
    name: 'Lily',
    age: '20',
    person: {
        name: 'Henry',
        age: '21'
    }
};
let obj22 = JSON.parse(JSON.stringify(obj21));
obj22.person.age = '25'; //不会改变obj31的person.age
console.log(obj21);
深拷贝方法2-迭代递归法for...in
//深拷贝方法2-迭代递归法for...in
let obj31 = {
    name: 'Lily',
    age: '20',
    time: ['13', '15'],
    person: {
        name: 'Henry',
        age: '21'
    }
};
function deepObject(obj){ //深拷贝
    let cloneObj = {};
    for(let key in obj){
        let objChild = Object.prototype.toString.call(obj[key]);
        cloneObj[key] = (objChild === '[object Array]' || objChild === '[object Object]') ? deepObject(obj[key]) : obj[key];
    }
    return cloneObj;
}
let obj32 = deepObject(obj31);
obj32.time[0] = '25'; //不会改变obj31的time值
obj32.person.age = '25'; //不会改变obj31的person.age
console.log(obj31);
posted @ 2019-11-28 17:20  shirliey  阅读(2403)  评论(0编辑  收藏  举报