참고링크
mdn web docs - Array.prototype.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);
}
});