Перейти до основного вмісту
← ⚡ JavaScript & the browser·Модуль C9 · Урок 5
ЗавданняCreate original = {date: new Date(0), nums: [1,2,3], set: new Set(['a','b'])}. structuredClone it. Mutate copy.nums.push(4) and copy.set.add('c'). Log original.nums.length (3), original.set.size (2), copy.nums.length (4), copy.set.size (3), and copy.date instanceof Date (true).

structuredClone — proper deep copy

100 XP7 min
Теорія

The right way to deep-copy

JSON.parse(JSON.stringify(x)) is the classic deep-copy hack, but:

  • Loses Date objects (become strings).
  • Loses Map and Set (become empty objects).
  • Loses undefined values (become missing keys).
  • Throws on cycles.

structuredClone is the standard answer since 2022:

const original = {
  d: new Date(),
  set: new Set([1, 2, 3]),
  nested: { arr: [1, 2, 3] },
};

const copy = structuredClone(original);
copy.nested.arr.push(4);
original.nested.arr.length; // 3, untouched

What it handles

Dates, Maps, Sets, ArrayBuffers, typed arrays, Blobs, even circular references. Symbols and functions don't survive (they're not serializable — same as JSON.stringify).

When to reach for it

Anywhere you'd previously use the JSON.parse hack — Redux state, undo stacks, "snapshot then mutate" patterns. C9-09 uses it for an undo stack.

🔒

Зареєструйся щоб кодувати

Теорія відкрита всім. Інтерактивний редактор, живий перегляд і перевірка відкриваються з 7-денним безкоштовним trial — потрібна картка, скасування у будь-який час.

Реєстрація — безкоштовний trial →

Перші 10 уроків у кожному треку — безкоштовні. Картка не потрібна.

← НазадНаступний урок →

Отримуй одну пораду з Python чи вебу — щодня поштою

Коротко, без води, без спаму. Відписка — в один клік.