如何用 JavaScript 乘奇数索引值


我们需要编写一个函数,传入数组数字文本作为唯一参数。位于偶数索引上的数字应按原样返回。而位于奇数索引上的数字应返回与它们对应的索引相乘的结果。

例如:

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
]

更新于:25-Aug-2020

302 次浏览

开启你的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.