gpt4 book ai didi

嵌套在生成器中的函数产生的 Javascript

转载 作者:IT老高 更新时间:2023-10-28 22:10:53 29 4
gpt4 key购买 nike

此代码生成错误:

function *giveNumbers() {
[1, 2, 3].forEach(function(item) {
yield item;
})
}

这可能是因为 yield 在一个不是生成器的函数内部。有没有一种优雅的方法来克服这个问题?我的意思是:

function *giveNumbers() {
let list = [1, 2, 3];
for (let i = 0; i < list.length; i++) {
yield list[i];
}
}

最佳答案

This is probably because yield is inside a function that is not a generator.

是的。您不能在回调中使用 yield

Is there an elegant way to overcome this?

取决于用例。通常,实际上想要从回调中yield 的理由为零。

在您的情况下,您需要一个 for...of 循环,它优于 almost every aspect 中的 .forEach无论如何:

function *giveNumbers() {
for (let item of [1, 2, 3])
yield item;
}

关于嵌套在生成器中的函数产生的 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34104231/

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