猿问

javascript中的生成器函数

我是 javascript 新手,无法理解生成器函数的这种行为。为什么它只输出奇数(1,3,5,7,9)?


function* numberGen(n){

    for (let i=0;i<n;i++){

        yield i

    }

}


const num = numberGen(10)

while (num.next().value!=undefined){

    console.log(num.next().value)

}


慕神8447489
浏览 102回答 3
3回答

潇潇雨雨

您num.next()在每次迭代中调用两次。您在while()标题中调用它一次以检查结果是否未定义,然后在正文中再次调用它以记录值。每个调用都从生成器中检索下一个项目。因此,您检查偶数项null,并在其后记录奇数项。相反,您应该将变量分配给单个调用function* numberGen(n){&nbsp; &nbsp; for (let i=0;i<n;i++){&nbsp; &nbsp; &nbsp; &nbsp; yield i&nbsp; &nbsp; }}const num = numberGen(10)let i;while ((i = num.next().value) !== undefined){&nbsp; &nbsp; console.log(i)}.next()您可以使用内置的for-of迭代方法,而不是显式调用该方法。function* numberGen(n) {&nbsp; for (let i = 0; i < n; i++) {&nbsp; &nbsp; yield i&nbsp; }}const num = numberGen(10)for (let i of num) {&nbsp; console.log(i);}

杨__羊羊

.next()您每次迭代调用两次,因此您会跳过所有其他数字。

侃侃尔雅

在 while 条件检查语句中,您消耗二分之一的值仅用于检查,迭代器是可消耗的,这就是为什么我们只看到奇数,偶数用于真实检查function* numberGen(n){&nbsp; &nbsp; for (let i=0;i<n;i++){&nbsp; &nbsp; &nbsp; &nbsp; yield i&nbsp; &nbsp; }}const num = numberGen(10);//using spread opertaor to iterate all valuesconsole.log([...num]);//or you can use forOf&nbsp;//for( number of num ){//&nbsp; console.log(number);//}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答