Middle
Ar kādām metodēm vai rīkiem jūs varat kopēt objektu JavaScript?
sobes.tech AI
Atbilde no AI
-
** Virsmas kopija:**
- Izplatīšanas operators (
...) Object.assign()
const original = { a: 1, b: { c: 2 } }; // Izplatīšana 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 } } - Izplatīšanas operators (
-
Dziļa kopija:
JSON.parse(JSON.stringify(obj))(ierobežojumi: nedarbojas ar funkcijām, undefined, Symbol, BigInt, cikliskām atsaucēm)- Strukturēta klonēšana (
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() {} }