Перейти до основного вмісту
← ⚡ JavaScript & the browser·Модуль C6 · Урок 9
ЗавданняGiven function* digits() yielding 1..5, log [...digits()].join(','). Then destructure const [first, second, ...rest] = digits() — log first, second, rest.join(',').

Spread + destructuring with iterables

100 XP7 min
Теорія

Spread on any iterable

The ... spread syntax calls [Symbol.iterator]() on whatever you spread. That means anything iterable works — Sets, Maps, strings, generators, NodeLists.

[...new Set([1, 2, 2, 3])];          // [1, 2, 3]
[..."abc"];                          // ["a", "b", "c"]
[...new Map([["a", 1], ["b", 2]])];  // [["a", 1], ["b", 2]]

function* g() { yield 1; yield 2; }
[...g()];                            // [1, 2]

Destructuring is iteration too

Array destructuring also calls the iterator protocol. The right side can be ANY iterable:

const [first, second] = new Set([10, 20, 30]); // 10, 20
const [a, b, ...rest] = generator();           // pulls 2 + rest

The unified mental model

for-of, [...x], new Set(x), Array.from(x), Promise.all(x) all call the iterator protocol. Once you implement Symbol.iterator (or write a generator), your value plays nicely with everything in the standard library.

🔒

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

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

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

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

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

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

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