Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

《你不知道的javascript》[中篇] generator有关如下代码运行结果为啥是 12 18, 自己计算12 24

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <link rel="stylesheet" href="">
</head>
<body>
<script  >

let a = 1;
let 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
    }
}

var s1 = step(foo);
var s2 = step(bar);

s2();
s2();
s1();
s2();
s1();
s1();
s2();
console.log(a,b)
</script>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

重点应该是第四个调用,即第三个 s2()。这个时候恢复执行的位置是 a = 8 + b,得到 a9,然后在 b = 9 * (yield 2) 的时候又暂停,这个时候 a 应该就已经是 9。最后一步调用的时候计算的应该是 9 * 2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...