[JavaScript] map()함수

홍싸리·2023년 5월 17일
0

javascript

목록 보기
2/18

참고링크
mdn web docs - Array.prototype.map()


map()

.map() 함수는 callbackFunction을 실행한 결과를 가지고 새로운 배열을 만들 때 사용한다.

array.map(callbackFunction(currentValue, index, array), thisArg);
arr.map(callback(currentValue[, index[, array]])[, thisArg]);

/*
* currentValue 	: 배열 내 현재 값
* index			: 배열 내 현재 값의 인덱스
* array			: 현재 배열
* thisArg		: callbackFunction 내에서 this로 사용될 값
*/

배열 5개의 값을 모두 꺼내 콘솔에 찍어보는 방법

let arr = [10, 20, 30, 40, 50];

//1. 기본 for문 방법
for(let i=0; i<arr.length; i++){
  console.log(arr[i]);
}

//2. 향상된 for문 방법:: arr 배열의 값을 item에 하나씩 담아오는 개념
for(let item of arr){
  console.log(item)
}

//3. map() 일반 함수 형태
arr.map(function(item, index){
  console.log(index + '번 값', item);
}
        
//4. map() 화살표 함수 형태
arr.map((item, index) => {
  console.log(index + '번 값', item);
});

보통 index를 이용해 어떤 작업을 할 땐 기본 for문을, index를 사용하지 않을 땐 향상된 for문을 사용한다고 하면,
이러한 두 가지 경우를 합친 상황에는 능동적으로 사용하기 위해 map() 함수를 사용하고는 한다.

index가 짝수인 값들만 객체 배열에서 뽑아내는 예제

const data = [
	{id: 0, name: '홍길동', age: 10},
    {id: 1, name: '강호동', age: 20},
    {id: 2, name: '유재석', age: 30},
    {id: 3, name: '이효리', age: 40},
    {id: 4, name: '장채연', age: 50},
];

data.map((item, index) => {
if(index % 2 == 0){
console.log(item);
}
});

profile
그럴싸한건 다 따라해보는 프론트엔드 개발자 준비중인 6년차 퍼블리셔

0개의 댓글