//递归实现深拷贝
Object.prototype.clone=function(){
console.log(this.constructor)
//创建变量,如果调用的是数组,创建数组,如果是对象,就创建对象
let a = this.constructor ===Array ? [] : {};
// 循环向 空数组或者空对象中进行添加属性和属性值
for(var e in this){
//console.log(e)
//判断添加的属性如果类型是对象或者数组的话,就调用clone方法进行拷贝,否则值添在属性上
a[e] = typeof this[e] === "object" ? this[e].clone() : this[e]
}
return a //最后返回新的数组或者对象
}
let arr = [1,[{name:111,obj:{age:88,arr:[1,2,{}]}}]]
let newarr =arr.clone()
arr[0]=99999999
arr[1][0].name='haha'
console.log(arr,newarr)
通过递归实现深拷贝
最新推荐文章于 2023-06-02 11:14:03 发布