JS 数组的深拷贝
const oldObj = {
name:"哈默",
age:20,
colors:['orange','green','blue'],
friend:{
name:"小夏"
}
}
// const newObj1 = oldObj;
// newObj1.name='小野';
// console.log('oldObj',oldObj);
// console.log('newObj1',newObj1);
function deepClone(obj){
if(typeof obj !== "object"|| obj == null){
return obj;
}
let result;
if(obj instanceof Array){
result = [];
}else {
result = {}
}
for(let key in obj){
if(obj.hasOwnProperty(key))
result[key] = deepClone(obj[key])
}
return result
}
const newObj2 = deepClone(oldObj);
newObj2.name = "小野";
console.log('oldObj',oldObj);
console.log('newObj2',newObj2);
运用循环递归 来进行数组的拷贝

浙公网安备 33010602011771号