在阅读本篇之前,你需要先了解生成器(Generator)的基础知识,如果还没有,请阅读
在生成器(Generator)中,return
语句的作用是指定最后一次.next()
函数调用时的value
值
在生成器(Generator)中,return
语句的作用是为最后一个.next()
函数调用设置value
值。我们先来看一个例子:
function* generator() {
yield 1;
}
let it = generator();
console.log(it.next()); // {value: 1, done: false}
console.log(it.next()); // {value: undefined, done: true}
从上面的例子,我们可以看到,第一次.next()
函数调用,返回的对象中,value
的值为yield
语句中指定的值,即1
;而第二次.next()
函数调用,返回的对象中,value
的值为undefined
。
为了说明return
语句在生成器(Generator)中的作用,我们再看一个例子:
function* generator() {
yield 1;
return 2;
}
let it = generator();
console.log(it.next()); // {value: 1, done: false}
console.log(it.next()); // {value: 2, done: true}
从第二个例子,我们可以看出,第二次.next()
函数调用返回的对象中,value
的值为2
,即return
语句中指定的值。
更多关于生成器(Generator)的探讨请参见: