浅拷贝:顾名思义只copy第一层的数据,如果属性值是对象类型,则只拷贝引用地址,拷贝前后的对象会同步变化
思路:创建一个新的对象,遍历旧的对象,旧值赋值给新值。
实现方法:
1、对象的assign方法
Object.assign(target, obj)
2、数组的slice方法
arr.slice();
3、手写浅拷贝
function shallowCopy(obj) {
if (!obj || typeof obj !== 'object') {
return;
}
let result = Array.isArray(obj) ? [] : {};
for (const key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
result[key] = obj[key];
}
}
return result;
}
深拷贝:顾名思义是深层次的拷贝,如果属性值是对象也是递归依此拷贝值。
思路:创建一个新对象,遍历旧对象依次赋值,若遇到引用类型,则递归遍历引用类型依次赋值
1、对象的转换方法
JSON.parse(JSON.Stringify(obj));
2、手写深拷贝
function deepCopy(obj) {
if (!obj || typeof obj !== 'object') {
return;
}
let result = Array.isArray(obj) ? [] : {};
for (const key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
result[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
}
}
return result;
}