본문 바로가기

개발 일기

[Javascript] .reduce() method에서 살짝 위기가 찾아옴 지금

const newNumbers = [1, 3, 5, 7];

const newSum = newNumbers.reduce((accumulator, currentValue) => {
  console.log('The value of accumulator: ', accumulator);
  console.log('The value of currentValue:', currentValue);
  return accumulator + currentValue;
}, 10)

console.log(newSum);

이 코드를 내가 짰는데...

 

이렇게 놓고 보니까 별로 안 어렵네?ㅋㅋㅋㅋㅋㅋ

괜찮은 것 같다

 

https://discuss.codecademy.com/t/logic-behind-foreach-and-callback-functions/438376/3?_gl=1*1uj56l*_ga*NTgzMDE1Nzg3NC4xNjYwNDYwNjY4*_ga_3LRZM6TM9L*MTY2NDYwNzU0OS40OC4xLjE2NjQ2MDc1NjUuNDQuMC4w 

 

Logic behind forEach and callback functions

Thank you. So, allFruits is the callback with a parameter of “element”, which forEach passes to after being told to loop through the “fruit” array?

discuss.codecademy.com

근데 이제 reduce method를 덧셈이 아닌 곱셈으로 활용해서 팩토리얼을 계산한다든가

아니면 문자열에 공백을 더해서 계산해 문장을 만든다든가 하는 real world example이 어렵다.

활용하고자 하면 무궁무진하게 활용 가능한 method인듯

 

https://trekinbami.medium.com/explanation-of-javascripts-reduce-with-a-real-world-use-case-f3f5014951e2

 

Explanation of javascript’s reduce() with a real world use case

Higher order functions (HOF) like map() and filter() accept a function as an argument, iterate over your array, and return a new array…

trekinbami.medium.com

이런 링크도 찾았는데 아직은 뭐라는지 잘 모르겠다...

그래도 한번 읽어는 봐야지 궁금하니까