简体   繁体   English

如何在JavaScript中使用嵌套函数作为生成器(使用“内部”收益)

[英]How to use nested functions as generator in javascript (using “inner” yields)

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

gives 8,false; 给出8,假; then 6,false; 然后6,false; then undefined,true; 然后是undefined,true; whereas

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

gives me three times undefined,true; 给了我三遍不确定的,真实的;

As I want the hidden structure of d1 (as inner-function), how can I proceed to still have the same result as on the first sample? 当我想要d1的隐藏结构(作为内部函数)时,如何继续获得与第一个样本相同的结果?

The d2 generator function doesn't yield nor return anything, so you only get undefined. d2生成器函数不产生也不返回任何东西,因此您只会得到未定义的信息。

You probably want to call it passing p argument, and yield each iterated value with yield* . 您可能希望通过p参数调用它,并使用yield*产生每个迭代的值。

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

For copy and past needs: that is the solution of Oriol working for me 对于复制和过去的需求:这是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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM