//把两个数组合成一个数组
//把两个对象合成一个对象
let arr1 = [1,2,3];
let arr2 = [4,5,6];
let arr3 = [...arr1,...arr2];
// console.log(arr3);
//只能拷贝一层
let obj1 = {
a:1,
b:{
b1:10
}
}
let obj2 = {
c:3,
d:4
}
// //把原来的 obj1放在新对象里面,用一个新的b,把原来的b也拷贝一份
let newObj1 = {...obj1,b:{...obj1.b}}
let obj3 ={...obj1,...newObj1}
obj1.b.b1=100
obj2.c= 5
console.log(obj3);
//深拷贝
function deepClone(obj,hash=new WeakMap()){
if(obj === null) return obj;
if(obj instanceof Date) return new Date(obj);
if(obj instanceof RegExp) return new RegExp(obj);
if(typeof obj !== 'object') return obj;
if(hash.has(obj)) return hash.get(obj);
let newClone = new obj.constructor;
hash.set(obj,newClone)
for (const key in obj) {
if (obj.hasOwnProperty.call(obj, key)) {
newClone[key] = deepClone(obj[key],hash)
}
}
return newClone
}
let obj = {name:{age:18}}
obj.xxx = obj;
console.log(deepClone(obj));