1.JSON
let obj = {
a: 'hello',
b: function () {},
c: undefined,
d: {
e: 'world'
}
}
let copy = JSON.parse(JSON.stringify(obj)); // {a, d}
// JSON实现深拷贝的优点:多级也可以实现深拷贝
// 缺点:函数,正则,undefined 无法拷贝
说到底,就是将对象序列化再转成对象,所以可以实现深拷贝。
2.Object.assign()
let copy = Object.assign({}, obj); // {a, b, c}
// 优点:可以拷贝函数、正则、undefined
// 缺点:不能多级深拷贝
3.for-in
const deepCopy = function (obj) {
if (typeof obj !== 'object') {
return undefined;
// return new Error('传入的不是一个对象');
}
let copy = obj instanceof Object ? {} : [];
for(let i in obj) {
if (typeof obj[i] === 'object') {
copy[i] = deepCopy(obj[i]);
} else {
copy[i] = obj[i];
}
}
return copy;
}