gpt4 book ai didi

JavaScript,为什么生成器失败?

转载 作者:行者123 更新时间:2023-12-01 03:47:44 24 4
gpt4 key购买 nike

我想编写一个简单的生成器,通过调用next来获取增加的值

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

为什么这个生成器只生成 2 个值?

我更改了代码

function* next_id() {

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

它确实有效,这确实让我感到困惑。

最佳答案

因为你只调用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 .

关于JavaScript,为什么生成器失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43448755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com