1 对象
1-1 展开
var obj = {
name:"cheng",
age:18
}
var a = {...obj};
a.id =1001;
console.log(a);
console.log(obj);
1-2 Object.assign
var a = Object.assign({},obj);
a.id =1001;
console.log(a);
console.log(obj);
2 数组嵌套对象
var arr = [{name:"cheng",age:18},{name:"zhang",age:19}];
var b = [...arr]; //当是数组嵌套对象的时候,实现的是一个浅拷贝
b.push({
name:"vue",age:15
})
b[0].name = "wang"
console.log(b);
console.log(arr);
var arr = [{name:"cheng",age:18},{name:"zhang",age:19}];
//深克隆算法
function deepClone(obj){
let result ;
if(Array.isArray(obj) || (typeof obj == "object") ){
if(obj instanceof Array){
result= [];
}else{
result = {};
}
for(let key in obj){
result[key] = deepClone(obj[key]);
}
}else{
return obj;
}
return result;
}
let res = deepClone(arr);