본문 바로가기
develop/javascript

[JS] map()에 관하여

by hyoE 2021. 9. 6.
반응형

 

map()에 대해 더 자세히 알아야 겠다는 생각이 들어 정리하기!

 

 

array.map(callbackFunction(currenValue, index, array), thisArg)

 

callbackFunction , thisArg  두 개의 매개 변수,

callbackFunction은 currenValue, index, array 세 개의 매개 변수.

 

currentValue : 처리할 현재 요소

index Optional : 처리할 현재 요소의 인덱스

array Optional : map()을 호출한 배열

thisArg Optional : callback을 실행할 때 this로 사용되는 값.

 

 

제곱근 구하기

let nums = [4, 9, 16, 25];
let result = nums.map(Math.sqrt);
// [2, 3, 4, 5]

 

2배의 수 구하기

let nums = [1, 2, 3, 4, 5]
let double = nums.map(function(num){ return num*2});
// [2, 4, 6, 8, 10]
let nums = [1, 2, 3, 4, 5]
let double = nums.map(num => num*2);
// [2, 4, 6, 8, 10]

두 개가 같다. 편의상 밑에 arrow function을 자주쓴다.

let nums = [1, 2, 3, 4, 5]

function double(num){ return num*2}

let doubleNum = nums.map(double)
// [2, 4, 6, 8, 10]

함수 선언문을 통해서도 작동 가능하다.

 

객체에 사용하기

let students = [
         {id:1, name:"james"},
         {id:2, name:"tim"},
         {id:3, name:"john"}
]

let names = students.map(student =>student.name);
// ['james', 'tim', 'john']

let names = students.map(student =>student.id);
//[1, 2, 3]
let test = [
          {name : "Leo", sex : "male" },
          {name : "Jessica", sex : "female" },
          {name : "John", sex : "male" }
]

let newObj = test.map(function(element, index){
          console.log(element); ... 1
          let Obj = {}
          Obj[element.name] = element.sex;
          return Obj;
});

console.log(newObj); ...2

1 // 
    {name : "Leo", sex : "male" }
    {name : "Jessica", sex : "female" }
    {name : "John", sex : "male" }
2//
     [{Leo: "male"}, {Jessica: "female"}, {John: "male}]

 

 

반응형

'develop > javascript' 카테고리의 다른 글

[JS] innerHTML & innerText  (0) 2021.09.27
[JS] 배열을 객체로  (0) 2021.09.10
[JS] 숫자 야구 게임 [2]  (0) 2021.08.31
[JS] 숫자 야구 게임 [1]  (0) 2021.08.30
[JS] 임의의 숫자 생성하기  (0) 2021.08.30

댓글