【问题标题】:forEach not changing values of arrayforEach 不改变数组的值
【发布时间】:2021-05-29 10:11:09
【问题描述】:
availableButtons.forEach(function(part, index) {
    console.log(this[index].title)
    // this[index].title = intl.formatMessage(this[index].title);
  }, availableButtons)

上面的代码打印控制台如下:

{id: "abc.btn.xyz", defaultMessage: "someMessage"}

这确认每个对象都有一个 id,但是当我尝试执行注释代码时,它会抛出一个错误,提示 [@formatjs/intl] An id must be provided to format a message.

我使用了相同的数组,但只使用了一个单独的对象,如下intl.formatMessage(availableButtons[0].title); 这给了我所需的结果,我只是无法弄清楚。我尝试了各种在 forEach 中传递值的方法,我错过了什么?

【问题讨论】:

  • 您好,能否提供minimal reproducible example您的问题,以便我们帮助调试?
  • intl使用的包是什么?
  • this[index] 只是part 时,为什么要将您正在迭代的数组作为thisArg 传递?您可能也不想在迭代数组时对其进行变异。如果您尝试增加或更改数组中的元素,您应该真正使用array.prototype.map 并映射到新的数组引用。

标签: javascript arrays reactjs foreach internationalization


【解决方案1】:

直接访问数组(availableButtons)并使用 forEach 更新(变异)。

availableButtons.forEach(function (part, index) {
  console.log("before: ", availableButtons[index].title);
  availableButtons[index].title = intl.formatMessage(this[index].title);
  console.log("after: ", availableButtons[index].title);
});

【讨论】:

    【解决方案2】:

    我认为Array#map 在这个领域更适合

    availableButtons.map(part => {
        return {
        ...part,
        title: intl.formatMessage(part.title)
        };
    });
    
    

    【讨论】:

      【解决方案3】:

      forEach 实际上并不改变数组。它只是在数组上调用的速记循环。很难提出解决方案,因为您的意图不明确。

      availableButtons = availableButtons.map(button => {
       //do your mutations here
      }
      

      可能是一个开始

      【讨论】:

        猜你喜欢
        • 2014-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-27
        • 2021-11-26
        • 2012-09-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多