【问题标题】:Why dosent fruit get assigned 'apple' in this generator function? [duplicate]为什么在这个生成器函数中给水果分配了“苹果”? [复制]
【发布时间】: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


【解决方案1】:

根据Mozilla Docs功能*

//next的第一次调用从函数开始执行到第一个yield语句

在获得 yield 语句之前,您必须先调用 next() 'init'

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()
g.next();
console.log( g.next().value)
console.log( g.next('apples').value )

【讨论】:

  • 答案应该有英文解释,而不仅仅是代码
  • next 的第一次调用从函数开始执行,直到第一个 yield 语句是一个 explenation...但是答案已编辑
最近更新 更多