03_生成器代替迭代器.js
关键代码
对比
function makeIterator(array) { let nextIndex = 0; return { next: function () { return nextIndex < array.length ? { value: array[nextIndex++], done: false } : { value: undefined, done: true }; }, }; } const it = makeIterator(['a', 'b']); console.log(it.next()); //=> { value: 'a', done: false } console.log(it.next()); //=> { value: 'b', done: false } console.log(it.next()); //=> { value: undefined, done: true } console.log('------------------------------------------------'); // ---------------------------------------------------- function* makeGenerator(array) { for (const item of array) { yield item; } } const gt = makeGenerator(['a', 'b']); console.log(gt.next()); //=> { value: 'a', done: false } console.log(gt.next()); //=> { value: 'b', done: false } console.log(gt.next()); //=> { value: undefined, done: true }
04_生成器代替迭代器_方式二.js
function* makeGenerator(array) { yield* array; } const gt = makeGenerator(['a', 'b']); console.log(gt.next()); //=> { value: 'a', done: false } console.log(gt.next()); //=> { value: 'b', done: false } console.log(gt.next()); //=> { value: undefined, done: true }
代码对比
关键代码
class Classroom { constructor(address, name, students) { this.address = address; this.name = name; this.students = students; } *[Symbol.iterator]() { yield* this.students; } } const c1 = new Classroom('Beijing', 'Xuexi', ['Alice', 'Bruce', 'Celina']); const iterator = c1[Symbol.iterator](); console.log(iterator.next()); //=> { done: false, value: 'Alice' } console.log(iterator.next()); //=> { done: false, value: 'Bruce' } console.log(iterator.next()); //=> { done: false, value: 'Celina' } console.log(iterator.next()); //=> { done: true, value: undefined } console.log('------------------'); for (let item of c1) { console.log(item); //=> Alice //=> Bruce //=> Celina }