<script>
function * d1 (p) {
p-=1;
yield p;
p-=2;
yield p;
}
var g=d1 (9);
var h;
console.log((h=g.next()).value+','+h.done+';');
console.log((h=g.next()).value+','+h.done+';');
console.log((h=g.next()).value+','+h.done+';');
</script>
给出 8,假;那么6,假;那么未定义,true; 而
<script>
function * d2 (p) {
function * d1 (p) {
p -=1 ;
yield p;
p -=2 ;
yield p;
}
d1(p);
}
var g=d2 (9);
var h;
console.log((h=g.next()).value+','+h.done+';');
console.log((h=g.next()).value+','+h.done+';');
console.log((h=g.next()).value+','+h.done+';');
</script>
给了我三次 undefined,true;
由于我想要 d1 的隐藏结构(作为内部函数),我怎样才能继续获得与第一个样本相同的结果?
最佳答案
d2
生成器函数不会产生也不返回任何内容,因此您只会得到未定义的结果。
您可能希望通过传递 p
参数来调用它,并使用 yield*
生成每个迭代值。
function * d2 (p) {
yield* function * d1 (p) {
p -= 1;
yield p;
p -= 2;
yield p;
}(p);
}
关于javascript - 如何在 javascript 中使用嵌套函数作为生成器(使用 "inner"产量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37213456/