일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- frontend
- 캡슐화
- 자바스크립트
- typeScript
- Hooks
- github
- 프론트엔드
- 웹개발
- 자바스트립트
- 타입스크립트
- 추상화
- 상속
- 부트캠프
- 투두앱만들기
- 노마드코더
- 불변성
- 패스트캠퍼스
- Props
- js
- 클래스
- Zustand
- OOP
- JavaScript
- REACT
- 논리연산자
- webdevelopment
- 객체지향프로그래밍
- Fetch
- CSS
- 리액트
Archives
- Today
- Total
connecting dots
JS | reduce - summing an array, for...of 본문
reduce
Executes a reducer function on each element of the array, resulting in a single value.
배열을 가져다가 점차 줄여가다가 하나의 값만 남기는 것
[3, 5, 7, 9, 11].reduce((accumulator, currentValue) => {
return accumulator + currentValue;
});
callback | accumulator | currentValue | return value |
first call | 3 | 5 | 8 |
second call | 8 | 7 | 15 |
third call | 15 | 8 | 24 |
fourth call | 24 | 11 | 35 |
accumulator: 줄여나가야 하는 대상, 총 합계
currentValue: 각각의 개별 요소
인수 추가 가능
const evens = [2, 4, 6, 8];
evens.reduce((sum, num) => sum + num, 100)
// 두 번째 인수 100은 sum에 대한 초기값으로 사용됨
// 즉 100에 num을 더해주는 것
for ... of
for...of 문은 배열이나 다른 iterable 객체(예: 문자열, NodeList 등)의 요소를 반복(iterate)하기 위해 사용됩니다.
const prices = [100, 200, 300, 400];
for (let price of prices) {
console.log(price);
}
// 100
// 200
// 300
// 400
const prices = [100, 200, 300, 400];
const sum = 0;
for (let price of prices) {
sum += price
}
console.log(sum) // 1000
for (let price of prices)는 prices의 각 요소를 하나씩 가져와 price 변수에 할당함
--> reduce
const total = prices.reduce((sum, price) => {
return sum + price
}
console.log(total) // 1000
최소값 구하기
const minPrice = prices.reduce((min, price) => {
if (price < min) {
return price;
}
else return min;
})
console.log(minPrice) // 100
반응형