代码之家  ›  专栏  ›  技术社区  ›  Bruno Mazza

在JavaScript ES6生成器中,yield关键字实际上是如何工作的?[副本]

  •  6
  • Bruno Mazza  · 技术社区  · 6 年前

    我正在处理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] ?很抱歉这个愚蠢的问题,但我真的很想能够完全理解这一点。提前感谢!

    1 回复  |  直到 6 年前
        1
  •  4
  •   thgaskell    6 年前

    调用 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]