为什么最后b
的值不是24而是18?
我认为上次调用函数 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);
最佳答案
在 bar
函数的最后一行:
b = a * (yield 2);
代码在运行 (yield 2)
之前已经运行了 a *
。所以看起来 a
在那个时候已经被评估了。
如果将 a
的乘法移动到 (yield 2)
之后,那么 a
似乎是在 (yield) 之后计算的2)
运行,从而确保您获得 a
的最新值。
所以 bar
函数的最后一行可以变成:
b = (yield 2) * a;
这可以在下面的示例中看到。
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);
关于javascript - 对javascript生成器函数感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45316801/