forEach, map 메소드는 배열에서 사용하는 메소드로, 배열의 각 요소에 대해 파라미터로 주어진 함수를 실행한다.
map 함수는 return이 있어 함수의 결과를 반환하는 것이 가능하다.
forEach
const arr = ['녹차','백차','홍차','허브차'];
arr.forEach((element, index) =>{
console.log(`요소: ${element}`);
console.log(`index: ${index}`);
});
위의 코드를 실행한 결과는 다음과 같다.
파라미터로 받은 콜백 함수의 파라미터는 요소, index, forEach 메소드를 호출한 배열이다.
index는 0부터 시작되며 배열과 index는 생략가능하다.
객체배열 각 요소의 key-value 를 이용해보자.
const person = [
{
name: '강지수',
age: 20,
gender: 'Male'
},
{
name: '김별',
age: 22,
gender: 'Female'
}
];
person.forEach((e, i) =>{
console.log(`
이름: ${e.name}
나이: ${e.age}
성별: ${e.gender}`);
});
출력은 다음과 같다.
forEach 메소드의 콜백함수 내에서 기존 배열 변경이 가능하다.
const arr = [1, 3, 5, 7, 9];
// 변경된다.
arr.forEach((e, i) =>{
arr[i] = e * 2;
});
console.log(arr); // [ 2, 6, 10, 14, 18 ]
// 변경되지 않는다.
arr.forEach((e, i) =>{
e++;
});
console.log(arr); // [ 2, 6, 10, 14, 18 ]
map
forEach와 비슷한 특징을 가지고있지만 위에서 언급했던 것처럼 return이 가능하다.
foreach보다 살짝 느리지만 배열에 값 할당이 필요한 경우에는 map이 더 빠르다.
const numArr = [1, 3, 5, 7, 9];
const numSquare = numArr.map((element, index)=> {
console.log(`요소: ${element}`);
console.log(`index: ${index}`);
return element ** 2
});
console.log(numSquare);
출력은 다음과 같다.
객체배열을 이용해 새 객체배열을 만들 수 있다.
const arr1 = [
{
prod_name: '오레오오즈',
full_price: 6000,
discount_price: 5000
},
{
prod_name: '후루트링',
full_price: 5000,
discount_price: 3500
}
];
const discount_percent = arr1.map((e) => {
return{
prod_name: e.prod_name,
discount_per: 100 - (e.discount_price / e.full_price) * 100 ,
};
});
console.log(discount_percent);
출력은 다음과 같다.
댓글