javascript 使用foreach获取总和

vu8f3i0k  于 2022-11-27  发布在  Java
关注(0)|答案(2)|浏览(151)

我试图通过在javascript中使用forEach来得到一个总数,但不知何故失败了...它只是列出了值,而不是给我总数

const finances = [
    ["Jan", 867884],
    ["Feb", 984655],
    ["Mar", 322013],
    ["Apr", -69417],
    ["May", 310503],
];

let sum2 = 0;
for (let i = 0; i < finances.length - 1; i++) {
  let monthDiff = finances[i][1] - finances[i + 1][1];
  // console.log(monthDiff)
//   console.log(typeof(monthDiff))
  const newArray = [monthDiff];
  // console.log(newArray)
  newArray.forEach((item) => {
    sum2 += item; 
    console.log(sum2); //listing values not giving me a total why?
  });
}
2lpgd968

2lpgd9681#

你必须循环遍历每个数组项,得到第一个索引,并将其与当前和相加。在第一次循环中,零是当前和。
循环编号1 -当前和= 0,当前值[1] = 867884
循环编号2 - csum = 867884,cval[1] = 984655
循环编号3 - csum = 867884 + 984655,cval[1] = 322013
...一直持续到数组结束

const finances = [["Jan", 867884], ["Feb", 984655], ["Mar", 322013], ["Apr", -69417], ["May", 310503]];
    
    const total = finances.reduce(
        (currentSum, currentValue) => currentValue[1] + currentSum
    , 0); // initial sum is zero
    
    console.log(total)

每一个

const finances = [["Jan", 867884], ["Feb", 984655], ["Mar", 322013], ["Apr", -69417], ["May", 310503]];
 
    let total = 0;
    finances.forEach(item => total = item[1] + total);
    console.log(total)
wtzytmuj

wtzytmuj2#

如果使用forEach不是强制的,我会切换到reduce。reduce为您提供了跟踪前一个值的选项,作为回调的第一个参数。有关更多信息,请遵循Link

const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue
);

console.log(sumWithInitial);
// expected output: 10

相关问题