示例工程 06-arrays-iterables-generators

06-arrays-iterables-generators/03-custom-iterable/main.js

javascript · 2.1 KB

运行:06 · 自定义可迭代对象

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

// main.js —— 可迭代协议:对象实现 Symbol.iterator 就能被 for...of / 展开 / 解构消费
// 迭代器必须返回 { value, done };提前退出时引擎会调用 return()。
 
export class Countdown {
  constructor(start) {
    this.start = start;
    this.log = [];
  }
 
  [Symbol.iterator]() {
    let n = this.start;
    const log = this.log;
    return {
      next() {
        if (n >= 0) return { value: n--, done: false };
        return { value: undefined, done: true };
      },
      return() {
        log.push('return');
        return { done: true };
      },
    };
  }
}
 
export function spreadValues() {
  return [...new Countdown(3)];
}
 
export function arrayFromValues() {
  return Array.from(new Countdown(2));
}
 
export function destructure() {
  const [a, b] = new Countdown(5);
  return [a, b];
}
 
export function manualIterator() {
  const it = new Countdown(1)[Symbol.iterator]();
  return [it.next(), it.next(), it.next()];
}
 
export function breakTriggersReturn() {
  const c = new Countdown(5);
  const seen = [];
  for (const value of c) {
    seen.push(value);
    if (value === 3) break;
  }
  return { seen, log: c.log };
}
 
export function repeatable() {
  const c = new Countdown(2);
  return { first: [...c], second: [...c] };
}
 
export function glyphs() {
  return [...'a😀b'];
}
 
export function run(log = console.log) {
  const br = breakTriggersReturn();
  const rows = [
    ['展开 Countdown(3)', JSON.stringify(spreadValues())],
    ['Array.from(Countdown(2))', JSON.stringify(arrayFromValues())],
    ['解构 [a, b]', JSON.stringify(destructure())],
    ['手动 next() 三次', JSON.stringify(manualIterator())],
    ['break 触发 return()', `${JSON.stringify(br.seen)} / log=${JSON.stringify(br.log)}`],
    ['同一个可迭代对象可重复消费', JSON.stringify(repeatable())],
    ["字符串按码点迭代 'a😀b'", JSON.stringify(glyphs())],
  ];
  log('场景 => 结果');
  for (const [label, value] of rows) log(`${label} => ${value}`);
  log('-'.repeat(50));
  log('要点:Symbol.iterator 返回迭代器;for...of 提前退出会调用迭代器的 return(),用于清理资源。');
  return rows;
}