如何将奇数索引值相乘JavaScript

我们需要编写一个函数,该函数将Number文字数组作为一个唯一的参数。位于偶数索引的数字应原样返回。但是,应返回位于奇数索引处的数字乘以其对应的索引。

例如-

If the input is:
   [5, 10, 15, 20, 25, 30, 50, 100]
Then the function should return:
   [5, 10, 15, 60, 25, 150, 50, 700]

我们将使用Array.prototype.reduce()方法构造所需的数组,该函数的代码为-

示例

const arr = [5, 10, 15, 20, 25, 30, 50, 100];
const multiplyOdd = (arr) => {
   return arr.reduce((acc, val, ind) => {
      if(ind % 2 === 1){
         val *= ind;
      };
      return acc.concat(val);
   }, []);
};
console.log(multiplyOdd(arr));

输出结果

控制台中的输出将为-

[
   5, 10, 15, 60,
   25, 150, 50, 700
]