JavaScript - 콜백 메서드

Mongs_sw·2023년 2월 7일

javascript

목록 보기
16/21
post-thumbnail

1. Map

Map은 콜백 함수를 받아 배열의 요소당 1번씩 실행한다.
그 다음 콜백의 반환 값을 이용해서 새로운 배열을 형성한다.

예시 1)

const numbers = [1,2,3,4,5,6,7,8,9,10]

// 각 요소를 제곱으로 늘리고자 할때
const square = numbers.map(function (num) {
	return num * num;
})

//함수 표현식
const square = numbers.map(num) {
	return num * num;
}

// 화살표 함수
const square = numbers.map(num => {
	return num * num;
}

// 암묵적 반환
const square = numbers.map(num => (
	num * num
))

// 한줄로
const square = numbers.map(num => num * num);

예시 2) 영화

const movies = [
	{
    	title: '아이언맨',
        score: 93
    },
    {
    	title: '슈퍼맨 비긴즈',
        score: 83
    },
    {
    	title: '올드보이',
        score: 95
    },
    {
    	title: '그루지'
        score: 68
    }
]

// 새로운 배열에 영화 제목만 출력
const titles = movies.map(function (movie) {
	return movie.tilte
})

원래 배열에 있던 요소를 하나씩 가져와 map 메서드를 통해 새로운 복제 배열에 저장.

2. filter

요소로 구성된 배열에서 필터링하여 조건식을 참 or 거짓으로 판별시키는 불리언 함수이다.

또한, 콜백이 특정 조건으로 인해 true 값을 반환하면 새로 필터링된 배열에 추가된다.

예시 1)

// 학생들의 신상정보를 배열로 나열
const students = [
	{
    	name: '철수',
        height: 178,
        birth: 1997
    },
    {
    	name: '영희',
       	height: 166,
        birth: 1999
    },
    {
    	name: '동희',
        height: 184,
        birth: 2001
    },
    {
    	name: '창수',
        height: 192,
        birth: 1996
    },
    {
    	name: '지수',
        height: 155,
        birth: 1995
    },
    {
    	name: '현지',
        height: 170,
        birth: 2003
    }
]

// 키가 170 이하인 학생들을 필터링하여 새로운 배열에 저장
const smaller = students.filter(student => {
	return student.height <= 170
})

smaller 
>
(3) [{…}, {…}, {…}]
0: {name: '영희', height: 166, birth: 1999}
1: {name: '지수', height: 155, birth: 1995}
2: {name: '현지', height: 170, birth: 2003}
length: 3
[[Prototype]]: Array(0)

// 위의 함수식을 간단하게 한줄로 표현
const smaller = students.filter(s => s.height <= 170)

함수를 전달해서 참이나 거짓을 반환하고 지정된 요소에 대해 참이 반환되면 필터링되어 새로운 배열에 추가된다.

filter 자체가 원본에서 필터링하고 추려내도 기존의 배열에 영향을 주진 않음.
//map을 통해 키가 작은 학생들의 이름만 출력하고자 할때
const smallerNames = smaller.map(student => student.name)

// 한줄로 필터링과 맵을 동시 작성할 때
students.filter(student => student.height <= 170).map(student => student.name);
profile
몽이아빠의 개발 일기

0개의 댓글