JavaScriptのreduceを使ってみる

September 18, 2022

reduce を使ってみる

let arr = [1, 3, 5, 7, 9]

let result = arr.reduce((prev, current) => {
  return prev + current
}, 0)
console.log(result)

コンソール

25

reduce に渡すcallback関数の第3引数 (currentIndex), 第4引数 (array) を使ってみる

let arr = [1, 3, 5]

let result = arr.reduce((prev, current, idx, arr) => {
  console.log('--- start ---')
  console.log('prev', prev)
  console.log('current', current)
  console.log('idx', idx)
  console.log('arr', arr)

  return prev + current
}, 0)
console.log(result)

コンソール

--- start ---
prev 0
current 1
idx 0
arr (3) [1, 3, 5]
--- start ---
prev 1
current 3
idx 1
arr (3) [1, 3, 5]
--- start ---
prev 4
current 5
idx 2
arr (3) [1, 3, 5]
9

参考


SHARE

Profile picture

Written by tamesuu