본문 바로가기

프론트엔드 공부/javscript

map과 forEach 차이

//map & forEach
//forEach는 아이템 갯수만큼 콜백함수를 반복(return값x)
//map은 아이템 갯수만큼 콜백함수를 반복 + 콜백 내부에서 return 키워드로
//반환 데이터를 새로운 배열로 만들어 사용 가능
const numbers =[1,2,3,4];
const fruits = ['apple','banana','cherry'];

const a = fruits.forEach(function(fruit,index){
  console.log(`${fruit}-${index}`);
}); //apple-0 bannan-1 cherry-2
console.log(a); //undefined

const b = fruits.map(function(fruit,index){
  return{
    id:index,
    name:fruit
  }
});
console.log(b);
/*
{
  id:0
  name:"apple"
}
{
  id:1
  name:"banana"
}
{
  id:2
  name:"cherry"
}
*/


++ 추가 

내부 return값이 객체데이터일때 arrow function 사용시 return은 제거하되, 소괄호로 객체를 감싸줘야한다 !!

 

const b = fruits.map(function(fruit,index){
  return{
    id:index,
    name:fruit
  }
});

//return값이 객체인 함수의 arrow function

const b = fruits.map((fruit,index) => ({id:index, name:fruit})
);