Middle
Με ποιες μεθόδους ή εργαλεία μπορείτε να αντιγράψετε ένα αντικείμενο σε JavaScript;
sobes.tech AI
Απάντηση από AI
-
Επιφανειακό αντίγραφο:
- Τελεστής Spread (
...) Object.assign()
const original = { a: 1, b: { c: 2 } }; // Spread const copySpread = { ...original }; console.log(copySpread); // { a: 1, b: { c: 2 } } // Object.assign const copyAssign = Object.assign({}, original); console.log(copyAssign); // { a: 1, b: { c: 2 } } - Τελεστής Spread (
-
Βαθύτερο αντίγραφο:
JSON.parse(JSON.stringify(obj))(περιορισμοί: δεν λειτουργεί με συναρτήσεις, undefined, Symbol, BigInt, κυκλικές αναφορές)- Δομημένος κλωνοποιητής (
structuredClone())
const original = { a: 1, b: { c: 2 }, d: function() {} }; // JSON.parse(JSON.stringify()) const copyJson = JSON.parse(JSON.stringify(original)); console.log(copyJson); // { a: 1, b: { c: 2 } } // structuredClone const copyStructured = structuredClone(original); console.log(copyStructured); // { a: 1, b: { c: 2 }, d: function() {} }