var oldObj = {
name: '范德彪',
age: '43',
designation: ['水库浪子','彪记靓汤总经理','彪哥解梦馆馆长'],
relationship: {
jiefu: '马大帅',
girl: '桂英',
}
}
function deepClone (obj) {
if (typeof obj !== 'object' || obj == null){
return obj;
}
let result;
if (obj instanceof Array){
result = [];
} else {
result = {};
}
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = deepClone(obj[key]);
}
}
return result;
}
var newObj = deepClone(oldObj);
newObj.age = 45;
newObj.designation[2] = "辽北精神分析研究所所长";
newObj.relationship.girl = "阿薇"
console.log('oldObj ',oldObj);
console.log('newObj ',newObj)
JS 手写深拷贝
最新推荐文章于 2025-04-01 11:32:29 发布