如何用 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 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP