How to Accurately Duplicate JavaScript Objects
JavaScript's built-in methods cannot guarantee the precise duplication of objects. This is due to the presence of prototype-derived properties and hidden attributes, which can lead to unforeseen results when cloning. To address this issue, various approaches have been developed.
2022 Update: Structured Cloning
A new JS standard called structured cloning provides a straightforward solution. It is supported by many modern browsers and allows for accurate duplication with the following syntax:
const clone = structuredClone(object);
Traditional Approach
In previous versions of JavaScript, a custom cloning function can be implemented using the following steps:
An example of a cloning function that addresses these challenges is provided below:
function clone(obj) { if (null == obj || "object" != typeof obj) return obj; // Handing different object types // ... implementation for Date, Array, and Object // Generic fallback: deep copy properties var copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; }
This function assumes that the object forms a tree structure and does not contain any cyclic references. Handling cyclic structures requires a more complex approach.
The above is the detailed content of How to Perfectly Clone JavaScript Objects?. For more information, please follow other related articles on the PHP Chinese website!