首页 > 其他 > 详细

深拷贝

时间:2020-06-21 09:52:29      阅读:67      评论:0      收藏:0      [点我收藏+]
function deepClone(obj={}){
if (typeof obj !== "object" || obj == null) {
// obj是null,或者不是数组对象,直接返回
return obj;
}
// 初始化返回结果
let result;
if (obj instanceof Array) {
result = []
} else {
result = {}
}
 
for (let key in obj){
// 保证key不是原型的属性
if(obj.hasOwnProperty(key)){
// 递归
result[key] = deepClone(obj[key])
}
}
// 返回结果
return result;
}
const obj1 = {
name: ming,
address:{
city: beijing
},
arr:[1,2,3]
}
const obj2 = deepClone(obj1);
obj2.address.city = hangzhou
console.log(obj1.address.city); // beijing

 

深拷贝

原文:https://www.cnblogs.com/liangzhixiaolaohu/p/13171128.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!