将数组简化为每个第 n 个元素的总和 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/11/24 23:40:17

我们需要编写一个 JavaScript 函数,该函数接受一个数字数组并返回数组中索引处存在的每个数字的累计和,该数字是数组中 n 的倍数。

让我们来编写该函数代码 −

const arr = [1, 4, 5, 3, 5, 6, 12, 5, 65, 3, 2, 65, 9];
const num = 2;
const nthSum = (arr, num) => {
   let sum = 0;
   for(let i = 0; i < arr.length; i++){
      if(i % num !== 0){
         continue;
      };
      sum += arr[i];
   };
   return sum;
};
console.log(nthSum(arr, num));

输出

以下是控制台中的输出 −

99

上面,我们添加了从索引 0 开始的每个第二个元素,即

1+5+5+12+65+2+9 = 99

相关文章


有用资源