Перейти до основного вмісту
← ⚡ JavaScript & the browser·Модуль C6 · Урок 3
ЗавданняBuild a countdown object with property from = 3 implementing Symbol.iterator so for (const n of countdown) yields 3, 2, 1. Log each value using for-of, then log [...countdown] (spread).

The iterator protocol

150 XP10 min
Теорія

What makes something iterable

A value is iterable if it has a method at the special key Symbol.iterator that returns an iterator object. An iterator has a .next() method that returns { value, done }.

const arr = [10, 20, 30];
const it = arr[Symbol.iterator]();
console.log(it.next()); // { value: 10, done: false }
console.log(it.next()); // { value: 20, done: false }
console.log(it.next()); // { value: 30, done: false }
console.log(it.next()); // { value: undefined, done: true }

for-of and the spread operator both call [Symbol.iterator]() under the hood.

Building your own iterable

Any object with the right shape becomes iterable:

const range = {
  from: 1,
  to: 3,
  [Symbol.iterator]() {
    let current = this.from;
    const end = this.to;
    return {
      next() {
        return current <= end
          ? { value: current++, done: false }
          : { value: undefined, done: true };
      },
    };
  },
};

for (const n of range) console.log(n); // 1, 2, 3
[...range];                              // [1, 2, 3]

This is the cheap-and-explicit version. Lesson C6-04 shows the same thing with much less ceremony using generators.

🔒

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

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

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

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

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

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

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