yield 关键字在 JavaScript ES6 生成器中是如何工作的



我正在处理 ES6 中的生成器,我想从概念上了解以下函数中发生了什么:

function* createNames() {
    const people = [];
    people.push(yield);
    people.push(yield);
    people.push(yield);
    return people;
}
const iterator = createNames();
iterator.next('Brian');
iterator.next('Paul');
iterator.next('John');
iterator.next(); // output: ["Paul", "John", undefined]

我的问题是:为什么忽略了第一次推送?数组不应该是类似people = ['Brian', 'John', 'Paul', undefined]的东西吗?很抱歉这个愚蠢的问题,但我真的很想能够完全掌握这一点。提前感谢!

调用createNames()不会执行生成器内部的任何代码。它创建一个迭代器的实例,并在第一次next()调用时开始执行。

const iterator = createNames(); 
// Iterator instance created, but hasn't executed yet.
iterator.next('Brian');
// creates the people array
// attempts to push, yields
iterator.next('Paul');
// pushes 'Paul'
// attempts to push, yields
iterator.next('John');
// pushes 'John'
// attempts to push, yeilds
iterator.next(); 
// pushes undefined
// returns ["Paul", "John", undefined]

最新更新