如何用 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