js深拷贝一个对象对象里面有数组
可以使用递归实现深拷贝,遍历对象的每一个属性,如果属性值是对象或者数组,则继续递归拷贝。
以下是一个简单的实现:
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
let result = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = deepClone(obj[key]);
}
}
return result;
}
使用示例:
const obj = {
a: 1,
b: [2, 3, 4],
c: {
d: 5,
e: [6, 7, 8]
}
};
const newObj = deepClone(obj);
console.log(newObj); // { a: 1, b: [2, 3, 4], c: { d: 5, e: [6, 7, 8] } }
newObj.b.push(9);
newObj.c.e.push(10);
console.log(obj); // { a: 1, b: [2, 3, 4], c: { d: 5, e: [6, 7, 8] } }
console.log(newObj); // { a: 1, b: [2, 3, 4, 9], c: { d: 5, e: [6, 7, 8, 10] } }
``
原文地址: https://www.cveoy.top/t/topic/gPCc 著作权归作者所有。请勿转载和采集!