微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

forEach 不改变数组的值

如何解决forEach 不改变数组的值

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 中传递值方法,我错过了什么?

解决方法

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

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

可能是一个开始

,

我认为 Array#map 在这个 vade 中效果更好

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

,

直接访问数组(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);
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。