ES6의 더 세련된 형태의 반복문을 정리하였다.
- forEach
- map
- fillter
- reduce
예시를 위해 다음과 같은 객체 배열을 활용한다.
const animals = [
{name:'lion', size: 'big', isAggressive: true, weight: 200},
{name:'monkey', size: 'medium', isAggressive: false, weight: 30},
{name:'cat', size: 'small', isAggressive: false, weight: 10},
{name:'rat', size: 'small', isAggressive: false, weight: 2}
]
forEach는 부가 기능없이 반복문을 돌려준다
animals.forEach( (animal) => {
console.log(animal.name);
})
"lion"
"monkey"
"cat"
"rat"
두번째 인자로 index를 주어 활용할 수 있다
animals.forEach( (animal, index) => {
console.log(index);
})
0
1
2
3
map은 어떠한 배열을 다른 형태의 새로운 배열로 재생산할 때 사용한다
return으로 재생산한 배열 중 어떠한 값을 남길지 지정해준다
const animalsNames = animals.map( (animal) => {
return `Animal's name is ${animal.name} and Size is ${animal.size}!`;
});
console.log(animalsNames);
"Animal's name is lion and Size is big!"
filter은 배열 안에서 특정 조건을 가진 요소들만 추출하는 반복문이다
검색 기능을 구현할때 유용
const smallAnimals = animals.filter( (animal) => {
return animal.size === 'medium';
});
console.log(smallAnimals);
[[object Object] {
isAggressive: false,
name: "monkey",
size: "medium",
weight: 30
}]
reduce는 배열 안의 값들의 합을 구할때 유용하게 사용된다
첫번째 인자에는 누적해서 더해진 값, 두번째 인자에는 현재 더할 값을 지정한다
const numbers = [1, 10,11, 23, 444];
const total = numbers.reduce( (acc, cur) => {
// acc : 총 더해진 값
// cur : 현재 더할 값
console.log(acc, cur);
return acc+cur;
});
console.log(total);
1 10
11 11
22 23
45 444
489
실제로는 객체 배열을 활용할 때 많이 사용된다
배열.reduce((누적값, 현잿값, 인덱스, 요소) => { return 결과 }, 초깃값);
주의할 점은 초기값을 설정해 주어야 한다는 점
const totalWeight = animals.reduce( (acc, cur) => {
return acc+cur.weight
}, 0)
console.log(totalWeight);
242