array.reduce(callback, initialValue) 로 구성

 

callback - > (accumulator, currentValue, currentIndex, array)

initalValue (option)

를 구성해서 array 에있는 값을 모두 더 할때 사용된다.

 

const arr = [1,2,3];

const result1 = arr.reduce((acc,value) => acc += value); //6

const result2 = arr.reduce((acc,value) => {acc += value}, 10); //16
const result2_1 = arr.reduce((acc,value) => acc += value, 10); //16

 

 

(참고) 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

 

'프로그래밍 > JavaScript' 카테고리의 다른 글

객체(Object), 객체 메소드  (0) 2023.08.03
배열 뒤집기  (0) 2023.07.30
Class  (0) 2023.07.13
Functions - arrow, map, filter  (0) 2023.07.12
콜백(callback)함수  (0) 2023.07.12

+ Recent posts