[英]Confused about javascript generator function
Why the value of the final b
is not 24 but 18? 为什么最后一个
b
值不是24而是18?
I think when function s2
is called the last time, a
is 12
and last
is 2
, so b
should be equal to 12 * 2 = 24
. 我认为最后一次调用函数
s2
时, a
为12
, last
为2
,因此b
应该等于12 * 2 = 24
。
let a = 1, 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) { let it = gen(); let last; return function () { last = it.next(last).value; }; } let s1 = step(foo); let s2 = step(bar); s2(); //b=1 last=undefined s2(); //last=8 s1(); //a=2 last=undefined s2(); //a=9 last=2 s1(); //b=9 last=9 s1(); //a=12 s2(); //b=24 console.log(a, b);
In the last line of the bar
function: 在
bar
函数的最后一行:
b = a * (yield 2);
the code already ran the a *
before running (yield 2)
. 该代码在运行之前已经运行了
a *
(yield 2)
。 So it would seem that a
is already evaluated at that point. 因此,它似乎是
a
已经在该点进行评估。
If you move the multiplication by a
to after (yield 2)
, then it seems a
is evaluated after (yield 2)
is run, thereby ensuring you get the most up to date value of a
. 如果将乘法乘以
a
到after (yield 2)
,那么看起来a
是在运行(yield 2)
之后求值的,从而确保获得a
最新值。
So the last line of the bar
function could become: 因此,
bar
函数的最后一行可能变为:
b = (yield 2) * a;
This can be seen in the example below. 在下面的示例中可以看到。
let a = 1, b = 2; function* foo() { a++; yield; b = b * a; a = (yield b) + 3; } function* bar() { b--; yield; a = (yield 8) + b; b = (yield 2) * a; } function step(gen) { let it = gen(); let last; return function () { last = it.next(last).value; }; } let s1 = step(foo); let s2 = step(bar); s2(); //b=1 last=undefined s2(); //last=8 s1(); //a=2 last=undefined s2(); //a=9 last=2 s1(); //b=9 last=9 s1(); //a=12 s2(); //b=24 console.log(a, b);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.