Home [JavaScript] map 함수란?
Post
Cancel

[JavaScript] map 함수란?


map 함수에 매개변수

1
2
const array = [1,2,3,4,5]
const newArray = array.filter((value,index,array)=>)

value: 요소값

  • 1
    2
    3
    4
    5
    6
    7
    
    const newArray = array.map((value, index, array) => console.log(value));
    //실행 결과
    1;
    2;
    3;
    4;
    5;
    

index: 현재 차례인 요소에 고유 번호

  • 1
    2
    3
    4
    5
    6
    7
    
    const newArray = array.map((value, index, array) => console.log(index));
    //실행 결과
    0;
    1;
    2;
    3;
    4;
    

array: 현재 다루고 있는 배열에 복사본

  • 1
    2
    3
    
    const newArray = array.map((value, index, array) => console.log(array));
    //실행 결과
    [1, 2, 3, 4, 5];
    

map 함수 사용 예시

map은 반환 조건이 true, false로 정해지는 filter 함수와 달리 return 되는 값으로 새 배열을 만든다.

1. 기존 값에 2배씩

  • 1
    2
    3
    4
    5
    
    const array = [1, 2, 3, 4, 5];
    const newArray = array.map((value) => value * 2);
    console.log(newArray);
    //실행 결과
    [2, 4, 6, 8, 10];
    

2. if문으로 3이상은 “*”

  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    const array = [1, 2, 3, 4, 5];
    const newArray = array.map((value) => {
      if(value>=3){
        return "*"
      }else{
        return value
      }
    });
    console.log(newArray);
    //실행 결과
    [1, 2, '*', '*', '*'];
    

3. Object(객체)형 배열

  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    const array = [
    {name:"최혜정",age:27},
    {name:"박연진",age:21},
    {name:"손명오",age:25},
    {name:"문동은",age:23},
    ];
    const newArray = array.map((value) => value.name);
    console.log(newArray);
    //실행결과
    ['최혜정', '박연진', '손명오', '문동은'];
    

map 함수는 기존의 배열은 변하지 않는 새로운 배열을 반환한다.

1
2
3
4
5
6
7
8
const array = [1, 2, 3, 4, 5];
const newArray = array.map((value, index, array) => value * 2);

console.log(array);
console.log(newArray);
//실행 결과
[1, 2, 3, 4, 5];
[3, 4, 5];

마치며

혹시 잘못된 정보나 궁금하신 게 있다면 편하게 댓글 달아주세요.
지적이나 피드백은 언제나 환영입니다.

This post is licensed under CC BY 4.0 by the author.