본문 바로가기

JavaScript

[Javascript] Array map 사용법

react에서 값을 여러개 가지고 있는 배열의 모든 값을 꺼낼 때 map을 많이 사용한다.

이번 포스팅에서는 이러한 배열에서 값 꺼내는 방법 중 map( )을 다뤄보겠다.

map()

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

 

 

구문

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

 

매개변수

callback : function

currentValue : 현재값

index Optional : 인덱스

 

1. arr.map (함수 (현재값, 인덱스) {

 

})

 

2. arr.map (function (변수, 변수) {

    return 값

})

 

3. arr.map ( (변수, 변수) => {

   return 값

})

 

=> { }을 사용하려면 반드시 return값을 사용해야 한다.

 

 

const arr1 = [10,20,30,40,50]
          arr1.map( function( item , idx) {
              return console.log(item , idx)  // 10 0, 20 1, 30 2, 40 3, 50 4
          })
          arr1.map( (item,index)  => console.log( item ))  // 10,20,30,40,50

          const data = [
              {id:1, name:'홍길동'},
              {id:2, name:'강호동'},
              {id:3, name:'김철수'},
              {id:4, name:'김을동'},
              {id:5, name:'김태리'},
          ]

          data.map( (item , index) => {
              return console.log(item.id , item.name, index )  
          })
          // 1 '홍길동' 0, 2 '강호동' 1, 3 '김철수' 2, 4 '김을동' 3, 5 '김태리' 4
          
         data.map( (item,idx) => console.log( item, idx ))
         // Object 0, Object 1, Object 2, Object 3, Object 4 배열 값

 

<참고>

map mdn

Array.prototype.map() - JavaScript | MDN (mozilla.org)

 

Array.prototype.map() - JavaScript | MDN

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

developer.mozilla.org

 

반응형