【问题标题】:How to use Array.prototype.reduce in generator with yield inside?如何在带有 yield 的生成器中使用 Array.prototype.reduce?
【发布时间】:2019-11-19 06:53:40
【问题描述】:

我想运行一个 reduce 函数,我想通过 yield 暂停它。 这是我尝试并失败的原因,因为错误: Uncaught SyntaxError: Unexpected identifier

function* abc() {
    return [1,2,3].reduce((accumulator, currentValue) => {
        accumulator.push(currentValue); 
        yield currentValue;
        return accumulator;
    }, []);
}

【问题讨论】:

  • 你不能。 yield 不跨越函数边界。你到底想做什么?
  • @FelixKling 我想暂停并恢复该功能,同时检查当前状态以确定是否恢复。
  • 您可以构建自己的reduce 版本,它可以做到这一点。

标签: javascript generator


【解决方案1】:

您不能在回调中使用yield - 任何yields 都必须直接在生成器函数中。您必须将 reduce 转换为其他内容。

function* abc() {
  const accumulator = [];
  for (const currentValue of [1, 2, 3]) {
    yield currentValue;
    accumulator.push(currentValue);
  }
  // do something with accumulator?
}

console.log(...abc());

【讨论】:

  • 我明白了。是否有任何提案表明数组函数可以接受生成器函数?
  • 我一个都没见过。除非给内置数组方法一个特殊的例外(那将是奇怪),否则可能很难甚至不可能指定。
猜你喜欢
  • 2021-09-05
  • 2017-08-29
  • 2016-04-10
  • 2011-11-02
  • 2017-07-07
  • 2017-07-07
  • 2020-04-07
  • 2017-10-04
  • 2020-08-18
相关资源
最近更新 更多