能详细解释下结果[a, b]=[12,18]吗?谢谢大家(我认为是12,24)?

<!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>



yuqingzhijie3596863
浏览 1703回答 2
2回答

fdsgasgg

代码执行到 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

慕瓜9220888

LQJKVDWOAXHHAIHYEQKOIZAXZSLGZJMVGEOYKXSKHRAIBVGGBTBGHAJIPTWRMNZVTNOTIBIOOJTGTBGNTSYWUKSOJTWQTHIUWLLHHCICEWSZTOAWAJRUZDMZRVXFBPFHZQNCRUDVXLXFHBUJXUEOLNKPJSVZMVGUFBTHBOQDFOOUTVRINTYOYEVRPUPVYLNPAEZEZYWZKOCZOYXSLQVWLSXXDCLRPBZXWDBGFLKBLDVJHEEGDWPKCCCMWNVELCUTFGDGUDZXGECMXHJCKATRRRDQMNAYTLXGQGOLAUXPSFLFNKDSCFQFOTQEBTQJPOQHPRVXMEIGUNGSOSJXNVNRXBZWDSCQYETSTCAXLELUXKZTOKRWVJGNTTGOJCCVCLZEHPBPPUDOGODQWKJHTDBOGVJJAHZEZTQZWKYNLNWJFZMIMNOAHICOBFJDMZUGGMGAENHZJOOLZFDNMEAWAUBZPR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DAVLKQWZDHTDGMVLXRLVIFHNJFTQEIWBJYEIMQADFUETEHBPRMCIIFPAXUPPCIICXUHGFLLOSURTVRIOZWQRQFCHERLBL

名分开就是姓名

这有什么好解释,12,18就是12,18咯
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript