javascript - 这个generator函数执行完后为什么是这个结果?
本文介绍了javascript - 这个generator函数执行完后为什么是这个结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
下面的代码执行完后,a、b的值分别是12、18,为什么不是12、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);
我的理解是最后一次调用s2的时候,s2的last是2,此时a的值是12,最后应该是 b = 12 * 2
,所以b怎么不是24呢?
附上3张调试过程图:
解决方案
函数记录了暂停时候的值吧
如果将bar函数这么写
c = (yield 2)
b = a * c;
此时将是12 24
这篇关于javascript - 这个generator函数执行完后为什么是这个结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文