iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 21
0
自我挑戰組

JavaScript Array x 學習筆記系列 第 21

[Day 21 | Array.prototype.reduce () ]

array.reduce()

是陣列裡的累加器

array.reduce() 方法會對陣列中的每一個元素由左至右做累加的動作

假設有一個陣列 [ 0, 1, 2, 3, 4, 5 ] 需要計算總數,

通常我們會使用for的方式來累加:

let arr=[0, 1, 2, 3, 4, 5]

let sum=0;
for(let i=0; i<arr.length; i++){
    sum+=arr[i]
}

console.log(sum)

另一種方式,也可以使用array.reuduce()


Syntax

array.reduce(function(accumulator , currentValue, currentIndex, arr),initialValue)

四個回傳值,分別是

  • accumulator - 上一輪累計加總
  • currentValue - 目前的值
  • currentIndex - 這一輪迭代索引
  • array - 陣列內容

initialValue - 表示累加的初始值


Example

算出以下陣列的總數(初始值為 10)

No acc currentValue index arr
1 10 0 0 [0,1,2,3,4,5]
2 11 1 1 [0,1,2,3,4,5]
3 13 2 2 [0,1,2,3,4,5]
4 16 3 3 [0,1,2,3,4,5]
5 20 4 4 [0,1,2,3,4,5]
6 25 5 5 [0,1,2,3,4,5]

let sum = [0, 1, 2, 3, 4, 5].reduce(function (acc, currentValue) {
	
	return acc + currentValue;

}, 10)  //初始值使用10

console.log(sum)

上一篇
[Day 20 | Array. prototype.map () ]
下一篇
[Day 22 | Array.prototype.reduceRight () ]
系列文
JavaScript Array x 學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言