본문 바로가기

정리

map()

 

 

map()

map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환한다.

배열 안의 각 원소를 변환할 때 사용!

 

 

 

 

 

 

구문

 

arr.map(callback(currentValue[, index[, array]])[, thisArg])

 

  • callback : 새로운 배열 요소를 생성하는 함수. 다음 세 가지 인수를 가진다.
  • currentValue : 처리할 현재 요소
  • index : 처리할 현재 요소의 인덱스
  • array : map()을 호출한 배열
  • thisArg : callback을 실행할 때 this로 사용되는 값

 

 

 

완전한 map() 메소드 구문

 

arr.map(function(element, index, array){ }, this);

콜백함수 function()은 각 배열 요소에 대해 호출되며, map() 메소드는 언제나 현재의 element와 그것의 index, 그리고 전체 array 객체를 해당 요소에 전달한다.

 

this인수는 콜백함수 내부에서 사용된다. 기본적으로 이 값은 undefined이다. 

 

 

 

반환 값

 

배열의 각 요소에 대해 실행한 callback의 결과를 모은 새로운 배열

 



 


 

 

 

예제

 

인자를 받는 함수를 사용하여 숫자 배열 재구성하기

const arr = [2,4,6,8];

const a = arr.map(x => x*2);  // [4,8,12,16]

const a = arr.map(function(num){
  return num * 2;
}); // [4,8,12,16]

 

 

map을 활용해 배열 속 객체를 재구성하기

const arr = [{key:1, value:10},
             {key:2, value:20},
             {key:3, value: 30}];
             
const a = arr.map(function(obj){
 const rObj = {};
 rObj[obj.key] = boj.value;
 return rObj;
}); // [{1:10}, {2:20}, {3:30}]

 

위와 같은 객체 배열을 순환 처리하기

let user = [
     {firstname : "min", lastname : "kim"},
     {firstname : "yong", lastname : "kwon"},
     {firstname : "sohye", lastname : "oh"}
];

let username = user.map(function(element){
     return `${element.firstname} ${element.lastname}`;
})

// ["min kim", "yong kwon", "sohye oh"]

 

 

 

forEach와 map

//배열 안의 모든 숫자를 제곱해서 새로운 배열을 만들고 싶다면

const arr = [1,2,3,4,5];

const squared = [];

arr.forEach(n => {
  squared.push(n*n);
});

// [1,4,9,16,25];

 

map을 사용하면

const arr = [1,2,3,4,5];

const square = n => n*n;
const squared = arr.map(square);
// [1,4,9,16,25]

 

변화 함수(위에선 square)를 꼭 이름을 붙여서 선언할 필요는 없다.

const squared = arr.map(n => n*n);

 

 

 

'정리' 카테고리의 다른 글

해시-해시테이블-해싱  (0) 2023.07.27
indexOf(), findIndex(), find()  (0) 2023.04.11
parseInt()  (0) 2023.04.10