[英]Iterating through generator in ES6
這段代碼
let func = function *(){
for (let i = 1; i < 5; i++) {
yield i;
}
}
let s = func().next();
console.log(s);
let s2 = func().next();
console.log(s2);
回報
Object {value: 1, done: false}
Object {value: 1, done: false}
所以基本上func一直產生第一個值。
但是當我換到
let f = func();
let s = f.next();
console.log(s);
let s2 = f.next();
console.log(s2);
它按預期工作。 為什么將func賦值給變量會產生這樣的差異?
在您的第一段代碼中,您始終在創建新的生成器實例。 我已將這些實例分配給單獨的變量以更清楚地說明這一點:
// first generator instance
let g = func();
// first call to next on the first instance
let s = g.next();
console.log(s);
// second generator instance
let g2 = func();
// first call to next on the second instance
let s2 = g2.next();
console.log(s2);
而在你的第二個片段中,你繼續迭代同一個生成器(分配給變量f
):
let f = func();
// first call to next
let s = f.next();
console.log(s);
// second call to next
let s2 = f.next();
console.log(s2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.