如何减少数组中的循环参数

问题描述 投票:0回答:1

我尝试在使用array.reduce时访问数组项。 item.ay属性是动态的。我必须陷入困境。但是我无法访问该项目。这是我的代码


objectKeys.forEach(ay => {
        let lastArray = this.personalDataset.reduce((a, item, index) => {
          return (
            a + (this.spendingGroups[index].yourRate / 100) * (1 + item.ay)
          );
        }, 0);
        chartArray.push((lastArray - 1) * 100);
      });
      console.log(chartArray);

此代码返回[nan,nan]数组。当使用reduce无循环并将其全部推入时。

javascript arrays reduce
1个回答
0
投票

尝试通过添加加号Number使用隐式转换为+

objectKeys.forEach(ay => {
    let lastArray = this.personalDataset.reduce((a, item, index) => {
      return (
        a + (this.spendingGroups[index].yourRate / 100) * (1 + (+item[ay]))
      );
    }, 0);
    chartArray.push((lastArray - 1) * 100);
});
console.log(chartArray);
© www.soinside.com 2019 - 2024. All rights reserved.