如果你有像这样的发电机,
function* f () {
// Before stuff.
let a = yield 1;
let b = yield 2;
return [a,b];
}
Run Code Online (Sandbox Code Playgroud)
然后,跑
var g = f();
// this question is over this value.
g.next(123); // returns: { value: 1, done: false }
g.next(456); // returns: { value: 2, done: false }
g.next(); // returns: { value: [ 456, undefined ], done: true }
Run Code Online (Sandbox Code Playgroud)
第一次调用.next()设置a为123和第二次调用设置b为456,但是在最后一次调用时.next()返回,
{ value: [ 456, …Run Code Online (Sandbox Code Playgroud) 我正在处理ES6中的Generator,从概念上讲,我想了解以下函数中发生的情况:
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]
Run Code Online (Sandbox Code Playgroud)
我的问题是:为什么忽略了第一次推送?数组不应该像people = ['Brian', 'John', 'Paul', undefined]吗?很抱歉这个愚蠢的问题,但是我真的很想能够完全掌握这个问题。提前致谢!