JavaScript
자꾸 까먹는 map()
kelly09
2025. 1. 29. 22:02
- 호출한 배열의 모든 요소에 주어진 함수를 호출한 결과로 채운 새로운 배열 생성.
- 원본 배열은 변경되지 않음.
=> 배열의 모든 요소를 하나씩 가져와서 주어진 함수에 넣어 처리한 결과로 새로운 배열을 만들어 주는 메서드.
🍰 구문
map(callbackFn)
map(callbackFn, thisArg)
- callbackFn: 배열의 각 요소에 대해 실행할 함수
- thisArg(선택 사항): callbackFn 안에서 this로 사용할 값
🍰 callbackFn의 세 가지 매개변수
- currentValue - 현재 처리 중인 요소의 값
- index - 현재 처리 중인 요소의 인덱스
- array - map() 메서드를 호출한 배열 자체
🍰 사용 예시
// currentValue 사용하기
const numbers = [10, 20, 30];
const doubled = numbers.map((value) => value * 2);
console.log(doubled); // [20, 40, 60]
// index 사용하기
const numbers = [10, 20, 30];
const result = numbers.map((value, index) => value + index);
console.log(result); // [10, 21, 32]
// array 사용하기
const numbers = [10, 20, 30];
const result = numbers.map((value, index, array) => {
console.log(array); // [10, 20, 30] (항상 원본 배열을 보여줌)
return value * 2;
});
console.log(result); // [20, 40, 60]
// thisArg 사용하기
const obj = {
multiplier: 3,
};
const numbers = [10, 20, 30];
const result = numbers.map(function (value) {
return value * this.multiplier; // this는 obj를 가리킴
}, obj);
console.log(result); // [30, 60, 90]