英文:
What is a good way to implement a deep clone function for nested objects in JavaScript?
问题
"我正在寻找一种可靠的方法来在JavaScript中实现深克隆函数,该函数可以创建一个对象的完整副本,包括所有嵌套属性和数组。虽然我已经尝试使用JSON.parse(JSON.stringify(obj))
进行浅克隆,但对于嵌套对象并不起作用,因为它只创建了一个浅层副本。我想找到一个能够处理具有复杂嵌套的对象克隆的健壮解决方案。
我尝试编写了一个递归函数,但它没有按预期工作。以下是我的当前实现:
function deepClone(obj) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
let clone = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
clone[key] = deepClone(obj[key]);
}
}
return clone;
}
// 使用示例:
let originalObj = {
name: 'John',
age: 30,
address: {
street: '123 Main St',
city: 'New York',
state: 'NY'
},
hobbies: ['reading', 'cooking', 'swimming']
};
let clonedObj = deepClone(originalObj);
然而,对clonedObj
或其嵌套属性进行的任何修改也会反映在originalObj
中。是否有人能够建议一种有效的解决方案,以实现一个正确处理JavaScript中嵌套对象的深克隆函数?您的帮助将不胜感激。谢谢!"
英文:
"I am looking for a reliable approach to implement a deep clone function in JavaScript that can create a complete copy of an object, including all nested properties and arrays. While I've tried using JSON.parse(JSON.stringify(obj))
for shallow cloning, it doesn't work for nested objects since it only creates a shallow copy. I want to find a robust solution that can handle cloning objects with complex nesting.
I've attempted to write a recursive function, but it's not functioning as intended. Here is my current implementation:
function deepClone(obj) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
let clone = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
clone[key] = deepClone(obj[key]);
}
}
return clone;
}
// Usage example:
let originalObj = {
name: 'John',
age: 30,
address: {
street: '123 Main St',
city: 'New York',
state: 'NY'
},
hobbies: ['reading', 'cooking', 'swimming']
};
let clonedObj = deepClone(originalObj);
However, any modifications made to clonedObj
or its nested properties also reflect in the originalObj
. Could someone suggest an effective solution to implement a deep clone function that properly handles nested objects in JavaScript? Your assistance would be greatly appreciated. Thank you!"
答案1
得分: 0
使用structuredClone函数
StructuredClone是一项新功能,可以用它深度复制对象、数组等。
链接 https://developer.mozilla.org/en-US/docs/Web/API/structuredClone
示例
const obj = {name: "Mark"}
let deepclone = structuredClone(obj)
deepclone.name = "JOHN"
console.log(deepclone.name) // JOHN
console.log(obj.name) // Mark
英文:
Use structuredClone function
StructuredClone is new feature by which u can deep copy the objects arrays etc
Link https://developer.mozilla.org/en-US/docs/Web/API/structuredClone
Examples
const obj = {name: "Mark"}
let deepclone = structuredClone(obj)
deepclone.name = "JOHN"
console.log(deepclone.name) // JOHN
console.log(obj.name) // Mark
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论