JavaScript Array.map() 메서드 구조 상세 설명
기본 구조
array.map(callback(currentValue[, index[, array]])[, thisArg])
각 부분별 상세 설명
1. array (배열 객체)
const numbers = [1, 2, 3, 4, 5];
numbers.map(/* callback 함수 */);
// numbers가 array에 해당
2. callback (콜백 함수)
배열의 각 요소에 실행될 함수입니다.
기본 형태
function callback(currentValue, index, array) {
// 변환 로직
return transformedValue;
}
3. currentValue (필수 매개변수)
현재 처리 중인 배열 요소의 값입니다.
const fruits = ['apple', 'banana', 'orange'];
fruits.map(function(fruit) {
// fruit는 currentValue
return fruit.toUpperCase();
});
// 결과: ['APPLE', 'BANANA', 'ORANGE']
4. index (선택적 매개변수)
현재 처리 중인 요소의 인덱스(0부터 시작)입니다.
const colors = ['red', 'green', 'blue'];
colors.map(function(color, index) {
// index는 0, 1, 2 순서로 전달됨
return `${index + 1}. ${color}`;
});
// 결과: ['1. red', '2. green', '3. blue']
5. array (선택적 매개변수)
map 메서드를 호출한 원본 배열입니다.
const numbers = [10, 20, 30];
numbers.map(function(number, index, originalArray) {
console.log(`현재 배열: [${originalArray}]`);
return number * 2;
});
// 콘솔 출력:
// 현재 배열: [10,20,30]
// 현재 배열: [10,20,30]
// 현재 배열: [10,20,30]
6. thisArg (선택적 매개변수)
콜백 함수 내에서 this로 사용할 값입니다.
const multiplier = {
factor: 5,
multiply: function(number) {
return number * this.factor;
}
};
const numbers = [1, 2, 3];
// thisArg 사용
const result1 = numbers.map(function(number) {
return this.multiply(number);
}, multiplier);
// 결과: [5, 10, 15]
// 화살표 함수는 this를 바인딩하지 않음
const result2 = numbers.map(number => this.multiply(number), multiplier);
// TypeError: this.multiply is not a function
실제 사용 예제
기본적인 사용법
const numbers = [1, 2, 3, 4, 5];
// 화살표 함수
const doubled = numbers.map(num => num * 2);
// 결과: [2, 4, 6, 8, 10]
// 일반 함수
const squared = numbers.map(function(num) {
return num * num;
});
// 결과: [1, 4, 9, 16, 25]
모든 매개변수 사용 예제
const items = ['a', 'b', 'c', 'd'];
const result = items.map(function(currentValue, index, array) {
return {
value: currentValue,
position: index,
total: array.length,
isFirst: index === 0,
isLast: index === array.length - 1
};
});
console.log(result);
/*
[
{ value: 'a', position: 0, total: 4, isFirst: true, isLast: false },
{ value: 'b', position: 1, total: 4, isFirst: false, isLast: false },
{ value: 'c', position: 2, total: 4, isFirst: false, isLast: false },
{ value: 'd', position: 3, total: 4, isFirst: false, isLast: true }
]
*/
thisArg 활용 예제
const person = {
name: 'John',
scores: [85, 90, 78],
adjustScores: function(bonus) {
return this.scores.map(function(score) {
return score + bonus;
}, this); // thisArg로 this 전달
}
};
console.log(person.adjustScores(5));
// 결과: [90, 95, 83]
// 화살표 함수와 함께 사용
const calculator = {
base: 100,
operations: [10, -5, 20],
calculate: function() {
return this.operations.map(operation =>
this.base + operation // 화살표 함수는 this를 lexical로 capture
);
}
};
console.log(calculator.calculate());
// 결과: [110, 95, 120]
React에서의 활용
컴포넌트 리스트 렌더링
const users = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 35 }
];
function UserList() {
return (
<div>
{users.map((user, index, array) => (
<UserItem
key={user.id}
user={user}
index={index}
totalUsers={array.length}
/>
))}
</div>
);
}
function UserItem({ user, index, totalUsers }) {
return (
<div>
<h3>{index + 1}/{totalUsers}. {user.name}</h3>
<p>나이: {user.age}</p>
</div>
);
}
주의사항
1. 콜백 함수는 순수 함수로 작성
// ❌ 나쁜 예: 부수 효과(side effect) 발생
const numbers = [1, 2, 3];
let sum = 0;
const badResult = numbers.map(num => {
sum += num; // 부수 효과
return num * 2;
});
// ✅ 좋은 예: 순수 함수
const goodResult = numbers.map(num => num * 2);
const totalSum = numbers.reduce((acc, num) => acc + num, 0);
2. sparse 배열 처리
const sparseArray = [1, , 3]; // 중간에 빈 요소
const result = sparseArray.map((num, index) => {
console.log(`Index ${index}: ${num}`);
return num ? num * 2 : 0;
});
// 콘솔 출력:
// Index 0: 1
// Index 2: 3
// 결과: [2, empty, 6]
정리
| 부분 | 설명 | 필수/선택 |
|---|---|---|
array |
map을 호출할 배열 | 필수 |
callback |
각 요소에 적용할 함수 | 필수 |
currentValue |
현재 처리 중인 요소 | 필수 |
index |
현재 요소의 인덱스 | 선택 |
array |
원본 배열 | 선택 |
thisArg |
callback 내에서 사용할 this 값 | 선택 |
이 구조를 이해하면 map 메서드를 더 효과적으로 사용할 수 있고, React에서의 리스트 렌더링도 더 잘 이해할 수 있습니다.
JavaScript Array.map ()
'프로그래머로의 여정' 카테고리의 다른 글
| JS에서 key는 무엇인가 (0) | 2025.09.04 |
|---|---|
| React에서 map을 사용할 때 key의 의미와 중요성 (0) | 2025.09.04 |
| CSS 의사 클래스 선택자(pseudo-class selector) 란? (0) | 2025.09.03 |
| _fonts.scss에서 밑줄(_)을 앞에 붙이는 이유 (0) | 2025.09.02 |
| 유틸리티 클래스(Utility Classes)란 (1) | 2025.09.01 |