【发布时间】:2025-11-27 10:55:02
【问题描述】:
标题说明了一切。
输出是:
starting
lol
undefined
0 undefined
预期:
starting // yield giving us back a string
lol // yield giving back result from bar()
'apples' // since the 'yield bar()' is 'replaced' by 'apples' via next('apples')
'0 apples' // the last yield should tell us what fruit is, but its undefined
代码:
const bar = () => 'lol'
function* foo1() {
yield 'starting'
let a = 0
let fruit = yield bar()
console.log(fruit) // <-- y no apples? I could even see 'lol' being here too.
yield `${a} ${fruit}`
}
let g = foo1()
console.log(g.next().value)
console.log(g.next('apples').value)
console.log(g.next().value)
【问题讨论】:
-
生成器最初是暂停的。第一个
next启动它们。 -
我看到有两个人理解了您的评论,但对我来说似乎并不明显。
-
为什么投反对票的人?有正在运行的代码,预期的输出......
-
尝试在每个
next调用中传入一个单独的值,这样可能会更清晰一些。g.next('a').value,g.next('b').value,g.next('c').value -
是的。 VLAZ 赢得胜利。
标签: javascript generator