数组中的交替加法乘法 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/4 18:20:17

我们需要编写一个 JavaScript 函数,该函数接受一个数字数组并返回元素的交替乘法和

例如 −

如果数组为 −

const arr = [1, 2, 4, 1, 2, 3, 4, 3];

那么输出应该像这样计算 −

1*2+4*1+2*​​3+4*3
2+4+6+12

输出应该是 −

24

示例

让我们为此编写代码 −

const arr = [1, 2, 4, 1, 2, 3, 4, 3];
const alternateOperation = arr => {
   const productArr = arr.reduce((acc, val, ind) => {
      if(ind % 2 === 1){
         return acc;
      };
      acc.push(val * (arr[ind + 1] || 1));
      return acc;
   }, []);
   return productArr.reduce((acc, val) => acc + val);
};
console.log(alternateOperation(arr));

输出

控制台输出:−

24

相关文章


有用资源