【问题标题】:generate yield for every item in array Generator JS为数组 Generator JS 中的每个项目生成产量
【发布时间】:2020-05-24 14:36:49
【问题描述】:

我正在努力使我的生成器更灵活

来自:

function *formValidationSequence () {
    yield someRef.current.func()
    yield someOtherRef.current.func()
    ...
} 

至此:

const array = [someRef, someOtherRef]

const handler = (array) => {
    const sequence = testSequence(function *() {
        yield* array.map(item => item.current.func())
    })
}

但它不起作用。我想为数组中的每个 ref/item 动态创建 yield,而不是立即调用它们。

应该怎么做?

【问题讨论】:

  • 为什么是map?为什么不for(const el of array) yield el.current.func()?
  • func() 在做什么,什么不工作?
  • @Jonas Wilms 是的,当然!我没想到。谢谢

标签: javascript generator


【解决方案1】:

你会的

 yield* iterable

这将从可迭代对象创建一个迭代器并产生它的所有值。现在你的迭代是从.map 返回的东西,它是一个已经包含所有计算结果的数组。要yield 一个接一个的项目,你需要一个for 循环,因为它可以被中断:

 for(const item of [someRef, someOtherRef])
   yield* item.current.func();

【讨论】:

    【解决方案2】:

    map 在调用yield* 之前将对数组中的每个项目执行该函数。如果您只想每次迭代调用一个函数,那么只需使用常规循环:

    function*() {
        for (const el of array) {
            yield el.current.func();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-04-06
      • 2017-07-01
      • 2011-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多