[010] 자바스크립트 (JavaScript) - reduce() 함수 사용

2023. 1. 4. 23:44프론트엔드개발/JavaScript

반응형

안녕하세요~ totally 개발자입니다.

 

Reduce

 

오늘 다룰 부분은 reduce 함수입니다. reduce 함수는 배열에 사용되며 callback function, initialValue(생략 가능)를 가질 수 있으며 accummulator, currentValue를 주로 인자로 전달하게 됩니다. 이 accmulator는 콜백 함수가 실행되며 return된 반환값을 계속 누적합니다. 

 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

 

Array.prototype.reduce() - JavaScript | MDN

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the a

developer.mozilla.org

const arr = [1, 2, 3, 4];

arr.reduce((acc, currentNo) => acc + currentNo);

제일 기본적인 reduce 함수의 예시입니다. 먼저 배열을 선언하여 1, 2, 3, 4의 integer 값을 넣어주고 arr 배열에 prototype로 되어 있는 reduce 함수를 사용하여 acc, currentNo를 parameter로 하여 acc + currentNo를 누적해서 더해서 총합을 구할 수 있습니다.

 

콘솔로 출력해본 모습입니다. 다음 시간에는 Promise에 대해서 살펴볼 것인데 이 reduce와 Promise와 같이 쓰여 비동기 프로그래밍에도 사용될 수 있습니다.

 

 

 

반응형