如何在javascript中使用嵌套函数作为生成器(使用“inner”yields)

How to use nested functions as generator in javascript (using "inner" yields)

本文关键字:使用 inner yields javascript 函数 嵌套      更新时间:2023-09-26
<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,假; 然后未定义,真;而

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

给了我三次未定义,真实;

由于我想要 d1 的隐藏结构(作为内部函数(,我怎样才能仍然获得与第一个样本相同的结果?

d2生成器函数既不产生也不返回任何内容,因此您只会获得未定义。

您可能希望将其称为传递p参数,并使用 yield* 生成每个迭代值。

function * d2 (p) {
  yield* function * d1 (p) {
    p -= 1;
    yield p;
    p -= 2;
    yield p;
  }(p);
}

对于复制和过去的需求:这就是 Oriol 为我工作的解决方案

<script>
function * d2 (p)     {
    function * d1 (p)     {
        p -=1 ;
        yield p;
        p -=2 ;
        yield p;          }
    yield * d1(p);    }
 // ^^^^^^^^ are the changes
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>