// 浅拷贝
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);