//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})
);
'프론트엔드 공부 > javscript' 카테고리의 다른 글
정적 메서드와 정적 프로퍼티 (0) | 2021.05.25 |
---|---|
정규식표현 + .find(),.findIndex,includes() (0) | 2021.05.25 |
number - toFixed,parseInt,parseFloat,Math (0) | 2021.05.21 |
String prototype - indexOf,length,slice,replace,match,trim (0) | 2021.05.21 |
class 상속과 확장 (0) | 2021.05.21 |