//浅拷贝
function shallowClone(target) {
if(typeof target === 'object' && target !== null){
if(Array.isArray(target)){
return [...target]
}else{
return {...target}
}
}else{
return target;
}
}
// const obj = {a:1,b:{m:2}}
// const cloneObj = shallowClone(obj);
// obj.b.m = 5;
// console.log('clone--',cloneObj)
// console.log('obj--',obj)
function deepClone1(target) {
return JSON.parse(JSON.stringify(target));
}
// const obj = {
// a: 1,
// b: { m: 2 },
// c: [1, 2, 3],
// // 不能克隆方法
// d() {},
// };
// 会造成循环引用
// obj.c.push(obj.b);
// obj.b.j = obj.c;
// const cloneObj = deepClone1(obj);
// obj.c.push(666);
// console.log(obj);
// console.log(cloneObj);
function deepClone2(target,map = new Map()){
if(typeof target === 'object' && target !== null){
const cache = map.get(target);
if(cache){
return cache;
}
const result = Array.isArray(target)?[]:{}
map.set(target,result)
for(const key in target){
if(target.hasOwnProperty(key)){
result[key] = deepClone2(target[key],map)
}
}
return result;
}else{
return target;
}
}
const obj = {a:1,b:{m:2}}
const cloneObj = deepClone2(obj);
obj.b.m = 5;
console.log('obj--',obj)
console.log('clone--',cloneObj)
console