배열 내장함수 map

Clém·2020년 12월 23일
0
post-thumbnail

map

배열의 원소를 변환할 때 사용한다.

예시)

const array = [1, 2, 3, 4, 5, 6, 7, 8];

const squared = [];
array.forEach((n) => {
  squared.push(n * n);
});

console.log(squared);

map을 사용하면

const array = [1, 2, 3, 4, 5, 6, 7, 8];

const square = (n) => n * n;
const squared = array.map(square);

console.log(squared);

따로 연산 함수를 만들고 map의 파라미터에 넣어준다.
아니면 파라미터안에 함수를 풀어서 넣어줄 수도 있다.

const squared = array.map((n) => n * n);

훨씬 더 간결한 코드를 작성할 수 있다.

profile
On my way to become a Web Publisher

0개의 댓글

관련 채용 정보