forEach 不改变数组的值
forEach not changing values of array
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 实际上并不改变数组。它只是在数组上调用的 shorthand 循环。很难提出解决方案,因为您的意图不明确。
availableButtons = availableButtons.map(button => {
//do your mutations here
}
可能是一个开始
我认为 Array#map
在这方面效果更好
availableButtons.map(part => {
return {
...part,
title: intl.formatMessage(part.title)
};
});
直接访问数组 (availableButtons) 并使用 forEach 更新 (mutate)。
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);
});
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 实际上并不改变数组。它只是在数组上调用的 shorthand 循环。很难提出解决方案,因为您的意图不明确。
availableButtons = availableButtons.map(button => {
//do your mutations here
}
可能是一个开始
我认为 Array#map
在这方面效果更好
availableButtons.map(part => {
return {
...part,
title: intl.formatMessage(part.title)
};
});
直接访问数组 (availableButtons) 并使用 forEach 更新 (mutate)。
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);
});