SW Engineer & Developer/React Craft
array.map() 아직 어색한...
ByteCraft
2025. 1. 26. 22:44
구분 |
array.map(callback(currentValue, index, array), thisArg) |
callback() : 배열 각 요소에 대히 호출되는 함수 - currentValue: 배열의 현재 처리 중인 요소. - index (선택): 현재 요소의 인덱스. - array (선택): map()을 호출한 원본 배열. thisArg : 콜백 함수 내부에서 this로 사용할 값. 생략하면 기본적으로 undefined입니다. |
Case 1. 2를 곱한 배열을 Return |
const numbers = [1, 2, 3, 4]; const doubled = numbers.map(num => num * 2); console.log(doubled); // [2, 4, 6, 8] |
Case 2. index를 활용한 |
const numbers = [10, 20, 30]; const modified = numbers.map((num, index) => num + index); console.log(modified); // [10, 21, 32] |
Case 3. 객체 배열 변환 |
const users = [ { id: 1, name: "Alice" }, { id: 2, name: "Bob" }, { id: 3, name: "Charlie" } ]; const userNames = users.map(user => user.name); console.log(userNames); // ["Alice", "Bob", "Charlie"] |
Case 4. React 활용 예 |
<input className='searchbar' placeholder='검색어를 입력하세요' /> <div className='list_wrapper'> {/* array.map(callback(currentValue, index, array), thisArg) */} {todo.map((item) => ( <div>{item.content}</div> ))} </div> |
참고자료 |
Array.prototype.map() 메서드가 뭐야? |