深浅拷贝,是我们在处理数据中一定会遇到的问题,浅拷贝是引用地址的拷贝,主要是针对object类型,新数据和原始数据会相互影响。深拷贝是值的拷贝,是单独一个内存空间,不会互相影响。
浅拷贝
js
import clone from "/node_modules/lodash-es/clone.js";
import cloneDeep from "/node_modules/lodash-es/cloneDeep.js";
const obj = {
name: "zs",
age: 18,
sex: "男",
address: {
province: "北京",
city: "海淀",
},
};
js
/**
* 浅拷贝
*/
const o = obj;
o.name = "ls";
console.log(o);
console.log(obj);
js
/**
* 浅拷贝
*/
const o = clone(obj);
o.name = "ls";
o.address.province = "上海";
console.log(o);
console.log(obj);
js
// concat() 方法用于连接两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。
// 但是是一个浅拷贝,如果数组中包含引用类型,则两个数组中该位置的元素是同一个对象
import cloneDeep from "/node_modules/lodash-es/cloneDeep.js";
const arr1 = [1, 2, 3];
const arr2 = [4, 5];
const arr3 = arr1.concat(arr2);
console.log("🚀 ~ arr3:", arr3);
arr2.push(6);
console.log("🚀 ~ arr2:", arr2);
console.log("🚀 ~ arr3:", arr3);
const arr1 = [1, 2, 3];
const arr2 = [4, 5, { name: "张三" }];
const arr3 = arr1.concat(arr2);
console.log("🚀 ~ arr3:", arr3);
arr2[2].name = "李四";
console.log("🚀 ~ arr2:", arr2);
console.log("🚀 ~ arr3:", arr3);
// 深拷贝
const arr4 = cloneDeep(arr1.concat(arr2));
arr2[2].name = "李四";
console.log("🚀 ~ arr4:", arr4);
console.log("🚀 ~ arr2:", arr2);
```js
//浅拷贝
const o = { ...obj };
o.address.province = "山东";
o.name = "zxy";
console.log("🚀 ~ o:", o);
console.log("🚀 ~ obj:", obj);
const o1 = {};
Object.assign(o1, obj);
o1.address.province = "山东";
console.log("🚀 ~ obj:", obj);
console.log("🚀 ~ o1:", o1);
深拷贝,lodash里面的方法
js
//深拷贝
const o = cloneDeep(obj);
o.address.province = "山东";
o.address.city = "济南";
console.log("🚀 ~ obj:", obj);
console.log("🚀 ~ o:", o);
递归,封装深拷贝
js
function fn(num = 5) {
if (num === 0) return;
console.log(num);
fn(--num);
}
fn();
function time() {
console.log(new Date().toLocaleTimeString());
setTimeout(time, 1000);
}
time();
//浅拷贝
const obj = {
name: "张三",
age: 20,
hobby: ["篮球", "足球"],
address: {
province: "广东省",
city: "广州市",
},
};
const o = {};
// for (let key in obj) {
// o[key] = obj[key];
// }
// o.hobby.push("羽毛球");
// console.log("🚀 ~ o:", o);
// console.log("🚀 ~ obj:", obj);
//深拷贝
function deepClone(target, source) {
for (let key in source) {
if (source[key] instanceof Array || source[key] instanceof Object) {
target[key] = source[key].constructor === Array ? [] : {};
deepClone(target[key], source[key]);
} else {
target[key] = source[key];
}
}
}
// 深拷贝
// deepClone(o, obj);
// o.hobby.push("羽毛球");
// console.log("🚀 ~ o:", o);
// console.log("🚀 ~ obj:", obj);
深拷贝JSON.parse(JSON.stringify(obj));
js
const o2 = JSON.parse(JSON.stringify(obj));
js
const o2 = {};
deepClone(o2, obj);
obj.hobby.push("羽毛球2222");
obj.address.city = "深圳";
console.log("🚀 ~ o2:", o2);
console.log("🚀 ~ obj:", obj);
参考结果