Symbol.iterator Turns Objects Into Iterables

Implement Symbol.iterator as a generator method so objects work with for of, spread, and destructuring, then drive the returned iterator manually with next.

JavascriptData Integrity

Code

javascriptsnippet
22 lines
// Symbol.iterator 是 for...of 的协议入口:实现它的对象都能被逐个消费
class Playlist {
  constructor(tracks) {
    this.tracks = tracks;
  }
  *[Symbol.iterator]() {
    for (const t of this.tracks) yield t.toUpperCase();
  }
}

const playlist = new Playlist(['intro', 'theme', 'credits']);

// for...of、展开、解构全部走同一个协议
for (const track of playlist) console.log('play:', track);
console.log('spread:', [...playlist]);
const [first, ...rest] = playlist;
console.log('first:', first, '| rest:', rest);

// 手动 next():迭代器是带 done 标记的一次性游标
const it = playlist[Symbol.iterator]();
console.log('manual:', it.next().value, '|', it.next().value);
console.log('third:', it.next().value, '| drained:', it.next().done);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

play: INTRO
play: THEME
play: CREDITS
spread: [ 'INTRO', 'THEME', 'CREDITS' ]
first: INTRO | rest: [ 'THEME', 'CREDITS' ]
manual: INTRO | THEME
third: CREDITS | drained: true

Inside the snippet

Symbol.iterator Turns Objects Into Iterables keeps everything in the class Playlist.

The nesting pairs for (const t of this.tracks) yield t.toUpperCase(); with for (const track of playlist) console.log('play:', track); — the inner runs once per outer step.

Module-level bindings hold the data — playlist, it — with no function scope in between.

Using it

Output lines are prefixed (play:, spread:, first:), making each step’s effect easy to spot.

Key statements

for (const t of this.tracks) yield t.toUpperCase();

Interactive Tools for This Topic

FAQ

Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `playlist`, `it`.