深拷贝
深拷贝是拷贝多层,每一层数据都会拷贝
1、JSON.parse(JSON.stringify())
JSON.stringify()进行深拷贝有弊端: 忽略value为function, undefind, symbol, 并且在序列化BigInt时会抛出语法错误:TypeError: Do not know how to serialize a BigInt
let data = {
a: undefined,
b: 2,
c: { x: 111 }
};
let newData = JSON.parse(JSON.stringify(data));
2、自定义递归深拷贝
const deepCopy = (obj) => {
if (!obj || typeof obj !== "object") return obj;
let result = {};
if (Reflect.toString.call(obj).indexOf("Array") > 0) {
result = [];
}
Object.keys(obj).forEach((key) => {
result[key] = deepCopy(obj[key]);
});
return result;
};
浅拷贝
浅拷贝是拷贝单层,更深层次的对象还是指向引用地址
1、Object.assign() || {...obj}
let aa = {
a: undefined,
func: function () {
console.log(1);
},
b: 2,
c: { x: "xxx", xx: undefined },
d: null,
e: BigInt(100),
f: Symbol("s")
};
let bb = Object.assign({}, aa); // 或者 let bb = {...aa}
aa.c.x = 111;
console.log(bb);
4、Object.create() && Object.getOwnPropertyDescriptors()
let aa = {
a: undefined,
func: function () {
console.log(1);
},
b: 2,
c: { x: "xxx", xx: undefined }
};
let bb = Object.create(null, Object.getOwnPropertyDescriptors(aa));
aa.c.x = 111;
console.log(bb);