iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 22
1
自我挑戰組

JavaScript Array x 學習筆記系列 第 22

[Day 22 | Array.prototype.reduceRight () ]

昨天提到reduce

那今天就來說說reduce的另一個兄弟 reduceRight吧

reduceRight

array.reduceRight() 跟reduce 的功能大同小異

差別在於, reduceRight 是由右至左開始做累加

reduceRight一樣會回傳四個參數


Syntax

array.reduceRight(function(accumulator , currentValue, currentIndex, arr),initialValue)
  • accumulator - 上一輪累計加總
  • currentValue - 目前的值
  • currentIndex - 這一輪迭代索引
  • array - 陣列內容

initialValue - 累加的初始值


Example


程式碼如下:

let sum = [0, 11, 12, 23, 14, 15].reduceRight(function (
  acc,
  currentValue,
  index,
  arr
) {
  return acc + currentValue;
},
10); //初始值使用10

console.log(sum); //10+15+14+23+12+11=85
No acc currentValue index arr
1 10 15 5 [0,11,12,23,14,25]
2 25 14 4 [0,11,12,23,14,25]
3 39 23 3 [0,11,12,23,14,25]
4 62 12 2 [0,11,12,23,14,25]
5 74 11 1 [0,11,12,23,14,25]
6 85 0 0 [0,11,12,23,14,25]

參考來源:
https://www.fooish.com/javascript/array/reduceRight.html


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

尚未有邦友留言

立即登入留言