<script>
// 递归深克隆 对象或者数组
function deepClone(params){
if(params === null){
// 判断传进来的是不是 null
return null
}else if(Array.isArray(params)){
// 判断传进来的是不是 array 数组
var newObj = []
}else{
// 判断传进来的是不是 obj 对象
var newObj = {}
}
for(let i in params){
if(typeof params[i] === 'object'){
// 如果 params[i] 是引用类型数据,就再次调用函数,进行递归
newObj[i] = deepClone(params[i])
}else{
// 数据是 基础数据类型
newObj[i] = params[i]
}
}
return newObj
}
let list =[]
for(let i=0;i<20;i++){
list.push({
id:i,
name:`${i+1}个`
})
}
let obj_new={
age:12,
name:'名字',
tel:'123456',
list:['数组1','数组2','数组3'],
fun(){
console.log('方法函数')
}
}
let newList = deepClone(list)
console.log('list和newList',list,newList)
// false表明两个新数组没有任何关联是深克隆 true 表面还是浅克隆
console.log('list === newList',list===newList) // false
let new_objNew = deepClone(obj_new)
console.log('new_objNew和obj_new',new_objNew,obj_new)
// false表明两个新数组没有任何关联是深克隆 true 表面还是浅克隆
console.log('obj_new === new_objNew',obj_new===new_objNew) // false
</script>
深克隆对象或者数组(使用递归函数)
最新推荐文章于 2024-05-03 11:08:18 发布