Skip to Content
BlogJavaScript 정리내장 객체map

map

map() 함수는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열로 반환한다.
(원본 배열은 변경되지 않는다)

map 형식

arr.map((value, index, array) => { // 각 요소를 변환해서 반환 return newValue })
  • value: 현재 처리 중인 요소값
  • index: 현재 요소의 인덱스
  • array: map()을 호출한 원본 배열
  • 반환값: 콜백에서 반환한 값들로 이루어진 새 배열


화살표 함수와 return

map() 콜백에서 return 관련해서 가장 헷갈리는 부분은 중괄호 {} 사용 여부다.

const users = [ { id: 1, name: 'gori' }, { id: 2, name: 'gildong' } ] // 중괄호가 없으면 표현식이 자동 반환된다 (암시적 return) const names1 = users.map(user => user.name) console.log(names1) // ['gori', 'gildong'] // 중괄호가 있으면 return을 직접 써야 한다 (명시적 return) const names2 = users.map(user => { return user.name }) console.log(names2) // ['gori', 'gildong'] //중괄호가 있는데 return이 없으면 undefined 배열이 된다 const wrong = users.map(user => { user.name }) console.log(wrong) // [undefined, undefined]


map 예제

const arr = [1, 2, 3] const res = arr.map((value, index, array) => { console.log(value) // 1, 2, 3 배열값 console.log(index) // 0, 1, 2 배열순서 console.log(array) // [1, 2, 3] 호출한 배열 return value * 2 }) console.log(res) // [2, 4, 6]

map 예제 실행 결과

1 0 [1, 2, 3] 2 1 [1, 2, 3] 3 2 [1, 2, 3] [2, 4, 6]


마지막 수정