#TIL 27일차(배열메서드)

앙꼬·2024년 5월 30일

부트캠프

목록 보기
27/59


.map

map 메서드는 배열의 각 요소에 대해 주어진 함수를 적용한 결과로 새로운 배열을 생성한다.

문법

array.map(callback(element, index, array), thisArg);
  • callback: 배열의 각 요소마다 호출되는 함수로, 세가지 인수를 받는다.
    • element: 현재 처리 중인 배열 요소
    • index: 현재 처리 중인 요소의 인덱스
    • array: 'map()'을 호출할 배열
  • thisArg: callback을 실행할 때, 'this'로 사용할 값 → 선택 사항

예시 코드

const numbers = [2, 4, 6, 8];
const mapA = numbers.map(number => number * 3);

console.log(mapA); // [6, 12, 18, 24]

.filter

제공된 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열을 생성한다.

문법

array.filter(callback(element, index, array), thisArg);

→ 기본 구조는 map()과 동일하다!

예시 코드

const numbers = [1, 5, 7, 9, 12];
const filterA = numbers.filter(number => number % 3 === 0);

console.log(filterA); // [9, 12]

.find

배열에서 주어진 조건을 만족하는 첫 번째 요소를 반환한다. 조건을 만족하는 요소가 없다면 'undefined'를 반환한다.

문법

array.filter(callback(element, index, array), thisArg);

→ find도 기본 구조는 map()과 동일하다!

예시 코드

const numbers = [3, 6, 9, 12];
const findA = numbers.find(number => number % 2 === 0);

console.log(findA); // 6

1줄 정리

  • map: 배열의 각 요소를 변형하여 새로운 배열을 생성한다.
  • filter: 배열의 각 요소 중 조건을 만족하는 요소들만 모아 새로운 배열을 생성한다.
  • find: 배열의 각 요소 중 조건을 만족하는 첫 번째 요소를 반환한다.
profile
프론트 개발자 꿈꾸는 중

0개의 댓글