// 浅拷贝
const shallow = {a: 1};
const new11 = shallow;
const new22 = {};
Object.assign(new22, shallow);
// 深拷贝
function deepClone(obj) { // 深拷贝方法
const result = Array.isArray(obj) ? [] : {};
for(var i in obj) {
if(Object.prototype.toString.call(obj[i]) === '[object Object]') {
result[i] = deepClone(obj[i]);
} else {
result[i] = obj[i];
}
}
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);