728x90

기존 배열(array)에 어떠한 function(연산)을 적용한 후 새로운 array를 만들고 싶을 때 사용하는 helper method
(for loop같은 반복문을 이용하고 싶지 않을 때)

💻Example Code

ex1)
const originArr = [ 1, 2, 3, 4, 5 ];
const populatedArr = originArr.map( num => num * 2 );

console.log(originArr);
console.log(populatedArr);

실행 결과(기존 array는 그대로 있다)

ex2)

const originArr = [ '1', '2', '3', '4', '5' ];
const populatedArr = originArr.map( charNum => Number(charNum) );

console.log(originArr);
console.log(populatedArr);

실행 결과(String이 Number로 변경된 것을 볼 수 있다)

😋 map()의 괄호 안에 내가 원하는 function을 넣고, 기존 array에 있는 모든 값(element)를 불러와 실행시킨다.
굉장히 자주 쓰이는 helper method로써 꼭 알아둬야할 helper다. ex2)와 같이 String -> Number로 변경시키고 싶을 때도 자주 사용한다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

 

Array.prototype.map()

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Math.ceil()  (0) 2020.01.18
Array.prototype.filter()  (0) 2020.01.11
Array.prototype.push()  (0) 2020.01.06
Array.prototype.pop()  (0) 2020.01.04
Array.prototype.unshift()  (0) 2020.01.04

+ Recent posts