浅度克隆与深度克隆:
浅度克隆:
基本数据类型为值克隆,引用数据类型仍为引用(内存地址)克隆。
let a = 1;
let b = a;
b = 2;
console.log(a,b); //1 2
let obj1 = {
k: 1
}
let obj2 = obj1; //引用类型直接赋值,克隆的是内存地址,指向的还是同一片内存空间
obj2.k = 2;
console.log(obj1,obj2); //{k: 2} {k: 2}
let obj1 = {
k1: 1,
k2: {
k2_1: 1
}
}
//...延展操作符与 Object.assign 克隆对象只有对象里的基本数据类型为深度克隆,
//对象里的引用类型还是浅度克隆
let obj2 = {...obj1}; //let obj2 = {}; Object.assign(obj2,obj1);
obj2.k1 = 2;
obj2.k2.k2_1 = 2;
console.log(obj1,obj2) //{k1: 1,k2: {k2_1: 2}} {k1: 2,k2: {k2_1: 2}}
深度克隆:
所有元素或属性均完全克隆,与原引用数据类型完全独立,即修改新对象的值时,原对象不会被修改。(赋值数据而不是地址)
let obj1 = {
k1: 1,
k2: {
k2_1: 1
}
}
let obj2 = JSON.parse(JSON.stringify(obj1)); //完全深度克隆
obj2.k1 = 2;
obj2.k2.k2_1 = 2;
console.log(obj1,obj2) //{k1: 1,k2: {k2_1: 1}} {k1: 2,k2: {k2_1: 2}}