function *foo(x) {
let y = 2 * (yield (x + 1))
let z = yield (y / 3)
return (x + y + z)
}
let it = foo(5)
console.log(it.next()) // => {value: 6, done: false}
console.log(it.next(12)) // => {value: 8, done: false}
console.log(it.next(13)) // => {value: 42, done: true}
解析:
首先 Generator 函數(shù)調(diào)用和普通函數(shù)不同误证,它會返回一個迭代器
當(dāng)執(zhí)行第一次 next 時继薛,5+1=6
當(dāng)執(zhí)行第二次 next(12) 時,傳入12愈捅,覆蓋了第一個next的返回值遏考,let y = 2 * 12,
所以第二個 yield 等于 2 * 12 / 3 = 8
當(dāng)執(zhí)行第三次 next 時蓝谨,傳入的參數(shù)會傳遞給 z灌具,所以x = 5, y = 24, z = 13
相加等于 42
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者