应用场景:在复杂类型的赋值运算中使用(**Array,Object**)
一、浅拷贝:即传值又传址
1-1、数据为简单数据类型
var arr=[1,2,3]
var b=arr
b.push(4)
console.log(arr) // 1,2,3,4
1-2、数据每项是复杂数据类型
var arr = [{name:"zheng"},{name:"zhang"},{name:"li"}]
var res = [...arr]
res[0].name="huang" // arr变了
res.push({name:"vue"})
console.log(arr) // [{name:"huang"},{name:"zhang"},{name:"li"}]
二、深拷贝:只传值不传址
2-1、数组为简单数据类型
var res=[1,2,3]
1、
var c=[]
res.forEach(item=>{
c.push(item)
})
c.push(4)
console.log(res); //[1,2,3]
console.log(c); // [1,2,3,4]
2、
c=[...res]
c.push(4)
console.log(res); //[1,2,3]
console.log(c); // [1,2,3,4]
3、
c=res.slice(0,)
c.push(4)
console.log(res); //[1,2,3]
console.log(c); // [1,2,3,4]
4、
c = [].concat(res)
c.push(4)
console.log(res); //[1,2,3]
console.log(c); // [1,2,3,4]
2-2、对象属性是简单数据类型
var obj = {name:"cheng",age:18}
// var a = {...obj}
var a = Object.assign({},obj)
obj.id = 100;
console.log(a) // {name:"cheng",age:18}
2-3、每项为复杂数据类型
var obj={name:{name:"xuan"}}
function deepClone(obj) {
let result;
if (obj instanceof Array || typeof obj == "object") {
if (obj instanceof Array) {
result = [];
}
else if (typeof obj == "object") {
result = {};
}
for (let key in obj) {
result[key] = deepClone(obj[key]);
}
return result;
}
else {
return obj
}
}
var res=deepClone(obj)
console.log(res)