var a = {name: '1111'};
var b = a;
b.name = '2222';
console.log(a.name); // 2222
複製代碼
要求修改b.name 不影響a的值bash
var a = {name: '1111'};
var b = {...a}
b.name = '2222';
console.log(a.name); // 1111
複製代碼
可是若是a爲多層嵌套對象,使用解構只能深拷貝最上級,沒法將第二層對象進行拷貝spa
var a = {a:'123',b:{c:'333'}}
var b = {...a};
b.a = 'yyy'
b.b.c =222;
console.log(a.a); // 123
console.log(a.b.c); // 222
複製代碼
var obj = Object.assign(target, sources);code
var a = {name: '1111'};
var b = Object.assign({}, a);
b.name = '2222';
console.log(a.name); // 1111
複製代碼
Object.assign()與解構同樣,只能深拷貝一級的對象對象
var a = {name: '1111'};
var b = JSON.parse(JSON.stringify(a));
b.name = '2222';
console.log(a.name); // 1111
複製代碼
使用JSON字符串進行深拷貝,多層嵌套對象也能夠進行深拷貝字符串
var a = {a:'123',b:{c:'333'}}
var b = JSON.parse(JSON.stringify(a));
b.a = 'yyy'
b.b.c =222;
console.log(a.a); // 123
console.log(a.b.c); // 333
複製代碼