<template>
<div>深拷贝</div>
</template>
<script>
export default {
created () {
let worker = {
name:"Mr.Huang",
age:18,
car:[
{
type:"bengchi",
num:1
},
{
type:"gaidilake",
num:1
}
],
wife:"beautiful"
}
let real = this.deepClone(worker)
real.car[0].num=2
console.log(worker,real);
},
methods: {
//判断数据类型
judgeType(value){
return Object.prototype.toString.call(value).slice(8, -1);
},
//递归实现深拷贝
deepClone(oldVal){
let t = this
//判断类型,如果不是引用类型,直接返回
if(typeof(oldVal) !== 'object'){
return oldVal
}
//根据接收到的参数判断生成一个新的引用类型数组还是对象
let newVal = this.judgeType(oldVal)===Array?[]:{}
if(t.judgeType(oldVal)===Array){//数组类型
for(let key in oldVal){
if(typeof(oldVal[key])==='object'){
newVal[key]=t.deepClone(oldVal[key])//在这里递归,记得需要用新的引用类型去接收
}else{
newVal[key]=oldVal[key]
}
}
}else{
for(let key in oldVal){//对象类型
if(oldVal.hasOwnProperty(key)){//hasOwnProperty(propertyName)方法 是用来检测属性是否为对象的自有属性,如果是,返回true,否者false; 参数propertyName指要检测的属性名;
if(typeof(oldVal[key])=='object'){
newVal[key]=t.deepClone(oldVal[key])
}else{
newVal[key]=oldVal[key]
}
}
}
}
return newVal
}
}
}
</script>
递归方法实现引用类型深拷贝
最新推荐文章于 2024-07-21 10:17:51 发布