如何在JavaScript中实现一个用于深度克隆嵌套对象的好方法?

huangapple go评论61阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月5日 22:49:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76407640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定