通过 JavaScript 累加数组元素来组成新数组


问题

我们要求编写一个 JavaScript 函数,它以上面数组 arr 作为第一个参数,以上面数字 num(num <= 数组长度)作为第二个参数

我们的函数应该累加数组 arr 的每个长度为 num 的连续子数组以组成新数组中的相应元素,最后返回新数组

例如,如果输入函数为 −

const arr = [1, 2, 3, 4, 5, 6];
const num = 2;

那么输出应为 −

const output = [3, 5, 7, 9, 11];

输出解释

因为 1 + 2 = 3,2 + 3 = 5,依此类推...

Learn JavaScript in-depth with real-world projects through our JavaScript certification course. Enroll and become a certified expert to boost your career.

示例

以下是代码 −

 实时演示

const arr = [1, 2, 3, 4, 5, 6];
const num = 2;
const accumulateArray = (arr = [], num = 1) => {
   const res = [];
   let sum = 0, right = 0, left = 0;
   for(; right < num; right++){
      sum += arr[right];
   };
   res.push(sum);
   while(right < arr.length){
      sum -= arr[left];
      sum += arr[right];
      right++;
      left++;
      res.push(sum);
   };
   return res;
};
console.log(accumulateArray(arr, num));

输出

以下是控制台输出 −

[3, 5, 7, 9, 11]

更新于: 21-4-2021

148 次浏览

开启您的职业生涯

完成课程取得认证

开始使用
广告