使用 for of 循环迭代生成器时,有没有办法将值传递回生成器?

在下面的代码中,当我手动调用 iterable.next('some value') 时,我可以传回一个值,但是 for of 循环似乎调用了没有任何值的 .next() 方法。

我希望我已经以一种可以理解的方式解释了这一点。

const test = function* generator() {
  const list = [1, 2, 3, 4]
  for (const x of list) {
    const data = yield x
    console.log(data)
  }
}
const iterable = test()
console.log(iterable.next())
console.log(iterable.next('test2'))

console.log('FOR OF LOOP')
for (const y of iterable) {
  console.log(y)
}

最佳答案

如果你想传回一些东西,你需要负责调用 next() 你不能只是将它委托(delegate)给 for…of

使用 while 循环执行此操作是惯用的,但您也可以使用 for 循环执行此操作。例如:

const test = function* generator() {
  const list = [1, 2, 3, 4]
  for (const x of list) {
    const data = yield x
    console.log("passed in value: ", data)
  }
}
const iterable = test()
console.log('FOR OF LOOP')
let message = 0
for (let y = iterable.next(); !y.done; y = iterable.next(++message)) {
  console.log(y.value)
}


while 循环:

const test = function* generator() {
  const list = [1, 2, 3, 4]
  for (const x of list) {
    const data = yield x
    console.log("passed in value: ", data)
  }
}

const iterable = test()
let message = iterable.next()
while(!message.done){
  console.log(message.value)
  message = iterable.next("some value")
}

关于javascript - 使用 for of 循环将值传递给生成器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53909064/

10-09 18:35
查看更多