2017-04-17 14 views
0

私はこの発電機はわずか2値を生成するのはなぜコールnextJavaScript、ジェネレータが失敗した理由

> var gg = next_id(); 
> function* next_id() { 

    var current_id = 1; 
    yield current_id; 
    current_id ++; 
    return current_id; 
} 

> gg.next() 
Object {value: 1, done: false} 
> gg.next() 
Object {value: 2, done: true} 
> gg.next() 
Object {value: undefined, done: true} 
> gg.next() 
Object {value: undefined, done: true} 

増加した値を取得するには、単純な発電機を書きたいですか?

そして、私はそれが本当に私は混乱して作られた、それが動作するコード

function* next_id() { 

    var current_id = 1; 
    while (1) { 
     yield current_id; 
     current_id ++; 
    } 
    return current_id; 
} 

を変更しました。

+0

thats発電機の動作方法 –

答えて

2

あなたは一度だけyieldを呼び出すので。これはあなたがやろうとしているものであるように見えます:

function* next_id() { 
 
    var index = 0; 
 
    while(true) 
 
    yield index++; 
 
} 
 

 
var gen = next_id(); 
 

 
console.log(gen.next()); 
 
console.log(gen.next()); 
 
console.log(gen.next());

は、発電機hereのマニュアルを参照してください。

0

yieldはループを必要とし、yieldはジェネレータの実行を停止するだけです。

returnの文は、ループが永久に実行されるため、に決して到達しませんでした。になりました。

function* next_id() { 
 
    var current_id = 1; 
 
    while (true) { 
 
     yield current_id; 
 
     current_id++; 
 
    } 
 
} 
 

 
var gg = next_id(); 
 

 
console.log(gg.next()); // { value: 1, done: false } 
 
console.log(gg.next()); // { value: 2, done: false } 
 
console.log(gg.next()); // { value: 3, done: false } 
 
console.log(gg.next()); // { value: 4, done: false }
.as-console-wrapper { max-height: 100% !important; top: 0; }