1.浅拷贝
既传值也传址
var arr =[1,2,3];
var b = arr;
b.push(4);
console.log(arr);
2.深拷贝
只传值
var arr = [1,2,3];
var b = arr.slice(0,);
arr.forEach(item=>{
b.push(item);
})
var arr = [{name:"cheng"},{name:"zhang"},{name:"li"}];
var res = [...arr];
res[0].name="huang";
res.push({name:"vue"});
console.log(arr);
var arr = [{name:"cheng"},{name:"zhang"},{name:"li"}];
var arr = [{name:"cheng"},{name:"zhang"},{name:"li"}];
var res = [...arr];
遇到复杂类型(array+object)如何实现深拷贝
var obj = {name:{name:"cheng"}};
function deepClone(obj){
/* 1.能够识别数组和对象了 */
let result;
if(typeof obj=="number" || obj == null || typeof obj=="boolean"||typeof obj=="string"){
return obj;
}
if(obj instanceof Array || typeof obj == "object"){
/* 2.对拷贝的值作初始值得设定 */
if(obj instanceof Array){
result = [];
}else if(typeof obj =="object"){
result = {};
}
/* 3.需要将obj克隆到result中 */
for(let key in obj){
result[key] = deepClone(obj[key]);
}
return result;
}
}
var res = deepClone(obj);
console.log(res)
简单数据类型实现深拷贝
1. {...obj}<br /> 2. Object.assign()
var obj = {name:"cheng",age:18};
// var a = {...obj};
var a = Object.assign({},obj);
obj.id= 100;
console.log(a);
3.vue深拷贝
name:<input type="text" v-model="newItem.name">
id:<input type="text" v-model="newItem.id">
<button @click="doAdd">添加</button>
<div v-for="item of arr">
{{item.name}}
</div>
new Vue({
el:"#app",
data:{
newItem:{
name:"",
id:""
},
arr:[
{name:"vue",id:1001},
{name:"html",id:1001},
{name:"css",id:1001}
]
},
methods:{
doAdd(){
var res = {...this.newItem}
this.arr.push(res)
}
}
})