reduce()
메서드는 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환한다.const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(previousValue, currentValue) => previousValue + currentValue,
initialValue
);
console.log(sumWithInitial);
// expected output: 10
리듀서 함수는 네 개의 인자를 가진다.
리턴 값 : 누적 계산의 결과 값.
reduce()
는 빈 요소를 제외하고 배열 내에 존재하는 각 요소에 대해 callback
함수를 한 번씩 실행하는데, 콜백 함수는 다음의 네 인수를 받는다.accumulator
currentValue
currentIndex
array