如何使用 forEach JavaScript 建立部分和列表
我們有一個這樣的數字陣列 —
const arr = [1, 1, 5, 2, -4, 6, 10];
我們要求編寫一個函式,該函式返回一個新的陣列,大小相同,但每個元素都是到該點為止的所有元素的和。
因此,輸出應如下所示 —
const output = [1, 2, 7, 9, 5, 11, 21];
讓我們編寫函式 partialSum()。此函式的完整程式碼為 —
示例
const arr = [1, 1, 5, 2, -4, 6, 10];
const partialSum = (arr) => {
const output = [];
arr.forEach((num, index) => {
if(index === 0){
output[index] = num;
}else{
output[index] = num + output[index - 1];
}
});
return output;
};
console.log(partialSum(arr));在此,我們遍歷陣列並不斷給輸出陣列的元素分配新值,該值是當前數字與其前驅的和。
輸出
因此,此程式碼的輸出將是 —
[ 1, 2, 7, 9, 5, 11, 21 ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP