배열 map함수

들블리셔·2022년 7월 14일
0

map함수는 배열의 내장함수 중 하나이고, 기존배열의 값에서 변경하고 그 값을 새로운 배열로 만들때사용한다.

기본문법

const arr = [1, 2, 3];
const mapTest = arr.map( (value, index, array ) => thisArg );

콜백함수 자리에 세개의 매개변수가 들어갈 수 있다.

value는 처리할 현재 요소이다.

const mapTest = arr.map((value, index, array) => value);
console.log(mapTest)    //[1, 2, 3]

index는 요소의 인덱스 이다.

const mapTest = arr.map((value, index, array) => value);
console.log(mapTest)    //[0, 1, 2]

array는 map()을 호출 한 배열이다.

const mapTest = arr.map((value, index, array) => array);
console.log(mapTest)    //[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

여기서 화살표 다음의 thisArg는 callback을 실행할 때 this로 사용되는 값이다.

보는 것 처럼 특정 값을 새로운 배열로 만들어낸다.


예시

const items = [
  {
    id: 1,
    text: 'hello'
  },
  {
    id: 2,
    text: 'bye'
  }
]

const texts = items.map(item => item.text);

console.log(texts);     //["hello", "bye"]

객체를 담은 배열에서 text로 이루어진 문자열만 새로운 배열로 나타낼 수 있다.

profile
나의 공부방

0개의 댓글