//浅拷贝方法封装copy(obj){let newObj={}for(let i in obj){
newObj[i]=obj[i]}return newObj
},insert(){this.list.push(copy(this.student))}
三、对象的深拷贝(可以拷贝引用数据类型)
应用实例,当对象中包含对象进行拷贝push数组中
问题:对象中原始数据类型会进行拷贝,对象类型不会进行拷贝
<div id="app"><form @submit.prevent="insert"><input type="text" v-model="student.name"><input type="text" v-model="student.age"><input type="text" v-model="student.girlfriend.name"><button>添加</button></form><ul><li v-for="item in list">
姓名:{{item.name}}
年龄:{{item.age}}
女朋友:{{item.girlfriend.name}}</li></ul></div>newVue({el:'#app',data(){return{student:{name:'',age:'',girlfriend:{name:''}},list:[]}},methods:{copy(obj){let newObj={}for(let i in obj){
newObj[i]=obj[i]}return newObj
},insert(){this.list.push(this.copy(this.student))}}})//结果是对象中的girlfriend对象不会拷贝
解决:使用递归对对象中的数据进行类型判断,如果是对象类型,进行递归继续拷贝
copy(obj){let newObj={}for(let i in obj){//对数据类型判断if(obj[i]instanceofObject){
newObj[i]=this.copy(obj[i])}else{
newObj[i]=obj[i]}}return newObj
},insert(){this.list.push(this.copy(this.student))}
浅谈对象的深拷贝和浅拷贝一、为什么使用对象的拷贝?1.在普通数据类型赋值 let a=10 let b=a a=20 console.log(a)//a=20 console.log(a)//b=10因为普通数据类型的变量和数值存放在栈内存中可以直接改变a与b没有任何关联2.在引用数据类型赋值 let obj1={ name:'小彭', age:20 } let obj2=obj1 obj1.name=