<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Document</title><script type="text/javascript">var a = 1;var b = 2;function *foo() {a++;yield;b = b * a;a = (yield b) + 3;}function *bar() {b--;yield;a = (yield 8) + b;b = a * (yield 2);}function step(gen) {var it = gen();var last;return function() {last = it.next( last ).value;console.log( a, b, last );};}var s1 = step( foo );var s2 = step( bar );s2();s2();s1();s2();s1();s1();s2();console.log( a, b );</script></head><body></body></html>
2 回答
已采纳
fdsgasgg
TA贡献19条经验 获得超12个赞
代码执行到 yield 时候才会交出执行权.
你认为是24是因为你认为bar最后一次执行时候a应该是12,其实a在s2执行yield 2时候已经赋值为9了,因为计算是从左到右执行的,
你可以结合下面的代码感受下
function* gen1(){ console.log('g1', a * (yield 2)) } function* gen2(){ console.log('g2', (yield 2) * a) } var g1 = gen1(), g2 = gen2(), a = 9 g1.next() g2.next() a = 12 g1.next(2) // 18 g2.next(2) // 24
添加回答
举报
0/150
提交
取消