function* helloWorldGenerator() {
yield 'hello';
yield 'world';
return 'ending';
}
var hw = helloWorldGenerator();
hw.next()
// { value: 'hello', done: false }
value 值指yield后面 執(zhí)行后 表達(dá)式的值,例如‘hello’
var m= yield 'hello'
m 是執(zhí)行后返回的值 即yield+表達(dá)式的值.yield表達(dá)式本身沒有返回值,或者說總是返回undefined。有return 返回 return 后的值
hw.next(j)
next方法可以帶一個(gè)參數(shù),該參數(shù)就會(huì)被當(dāng)作上一個(gè)yield表達(dá)式的返回值(yield+表達(dá)式的值) j指上一次表達(dá)式中的返回的值
例子:解析
function* foo(x) {
var y = 2 * (yield (x + 1));
var z = yield (y / 3);
return (x + y + z);
}
var a = foo(5);
a.next() // Object{value:6, done:false}
a.next() // Object{value:NaN, done:false}
a.next() // Object{value:NaN, done:true}
var b = foo(5);
b.next() // { value:6, done:false }
b.next(12) // { value:8, done:false }
b.next(13) // { value:42, done:true }