next() 方法返回一个对象,这个对象包含两个属性 done
和 value
。可以向该方法传递一个参数以向生成器传值。
语法
gen.next(value)
参数:要发送给生成器(Generator
)的值。该值将作为yield表达式的结果进行赋值。比如在 [variable] = yield [expression]中,传递给.next()
函数的参数值将分配给[variable]。(The value to send to the generator. The value will be assigned as a result of a yield expression. i.e in [variable] = yield [expression], the value passed to the .next function will be assigned to [variable])
返回值:返回一个包含两个属性(done
和value
)的对象
-
done (布尔类型):
– 如果迭代器超过迭代序列的末尾,则值为 true。 在这种情况下,value可选地指定迭代器的返回值;
– 如果迭代器能够生成序列中的下一个值,则值为false。 这相当于没有完全指定done属性 -
value:迭代器返回的任意的Javascript值。当 done 的值为 true 时可以忽略该值。
举例一:
function* gen(){
yield 'happy';
yield 'chen';
yield 666;
}
let g = gen(); //返回一个生成器对象
console.log(g);
console.log(g.next());
console.log(g.next());
console.log(g.next());
console.log(g.next());
// Object [Generator] {}
// { value: 'happy', done: false }
// { value: 'chen', done: false }
// { value: 666, done: false }
// { value: undefined, done: true }
举例二:向生成器传值(next is called with a value. Note that the first call did not log anything, because the generator was not yielding anything initially.)
function* gen(){
while(true){
let variable = yield null;
console.log(variable);
}
}
let g = gen();
console.log(g.next(1));
console.log(g.next(2));
console.log(g.next(3));
//第一次没有打印 variable 的值
// { value: null, done: false }
// 2
// { value: null, done: false }
// 3
// { value: null, done: false }