使用JSON.parse(JSON.stringify(obj))是我见过很多用于深度复制对象的老技巧。它是否创建了对象的真正“深层复制”?从性能角度来看,使用它是否明智?
根据此处给出的示例,
let first:number[] = [1, 2];
let second:number[] = [3, 4];
let both_plus:number[] = [0, ...first, ...second, 5];
console.log(`both_plus is ${both_plus}`);
first[0] = 20;
console.log(`first is ${first}`);
console.log(`both_plus is ${both_plus}`);
both_plus[1]=30;
console.log(`first is ${first}`);
console.log(`both_plus is ${both_plus}`);
Run Code Online (Sandbox Code Playgroud)
传播显示了一个深层副本,因为所有三个数组都有自己的重复项,基于以下输出:
both_plus is 0,1,2,3,4,5
first is 20,2
both_plus is 0,1,2,3,4,5
first is 20,2
both_plus is 0,30,2,3,4,5
Run Code Online (Sandbox Code Playgroud)
文件说:传播创造了一个浅拷贝first和second。我怎么理解这个?
我得到的输出是 5,但我假设是 3。背后的逻辑是什么以及如何使输出 3。
const obj = {
a: 1,
b: 2,
c: {
p: 3
}
}
const obj1 = { ...obj}
obj.c.p = 5
console.log(obj1.c.p)Run Code Online (Sandbox Code Playgroud)