在 JavaScript 中将数字数组转换为累积和数组

javascriptweb developmentobject oriented programmingfront end technology更新于 2026/1/18 2:52:17

我们有一个像这样的数字数组 −

const arr = [1, 1, 5, 2, -4, 6, 10];

我们需要编写一个函数来返回一个新数组,该数组的大小相同,但每个元素都是该点之前所有元素的总和。

因此,输出应类似于 −

const output = [1, 2, 7, 9, 5, 11, 21];

因此,让我们编写函数 partialSum(),

该函数的完整代码如下 −

const arr = [1, 1, 5, 2, -4, 6, 10];
const partialSum = (arr) => {
   const output = [];
   arr.forEach((num, index) => {

      if(index === 0){
         output[index] = num;
      }else{
         output[index] = num + output[index - 1];
      }
   });
   return output;
};
console.log(partialSum(arr));

在这里,我们迭代数组,并每次都为输出数组的元素分配一个新值,该值是当前数字与其前一个数字的总和。

控制台中代码的输出将是 −

[
   1, 2, 7, 9,
   5, 11, 21
]

相关文章


有用资源