-
[TIL] Today I Learned : 배열의 반복문 - .forEach() / .map() 차이프론트엔드 개발자가 될거야./js 2022. 6. 24. 21:46
for문처럼
array의 반복문으로 사용되는 map, forEach 메서드를 공부해보았다.
둘 다 정말 많이 쓰이는 메서드라는데...
무슨 차이가 있을까??
일단 공통점은
두 메서드 모두 원본 배열을 건들지 않는 것이다.
원본 배열을 가지고 어떤 짓을 해도
원본 배열은 원래의 값을 그대로 가지고 있다. ✍🏻✍🏻✍🏻
그리고 arrow function은 map메서드와 forEach메서드와 같이 자주 쓰이니
arrow function에 대한 이해를 확실히 해야한다.
* 참고
arrow function을 가장 많이 사용할 때는 callback 함수로 사용할 때이다.
callback 함수란, 인자로 전달되는 함수라고 생각하면 된다.
Array.map()
아래는 map 메서드에 대한 설명이다.
https://www.robinwieruch.de/javascript-map-array/
forEach와의 차이점은
map메서드는 return을 해주고 새로운 배열을 만들어 준다는 것이다.
const arr = [1, 2, 3]; const squares = arr.map(function (x) { return x * x; });
이렇게 Array 타입의 데이터를 요소 갯수 만큼 반복하는데
해당 요소를 수정하고 싶은대로 로직을 구현하고 return해주면,
return 된 값으로 새 배열을 만들 수 있는 것이다.
그래서
squares = [ 1, 4, 9 ]
이렇게 새 배열이 탄생했다!!!!!!!!!
Array.forEach()
forEach는 for대신 사용하는 반복문이다.
map 과의 큰 차이는 forEach 함수 자체가 return 하는 것도 아무것도 없다는 것이다.
그냥 forEach 함수를 탈출하고 싶을 때 return 을 사용하면 된다.
map 은 요소가 수정된 새로운 배열이 return 되었다면,
forEach 는 아무것도 return 하는 것이 없다.
그래서 forEach 로 전달되는 callback 함수에서도 return하는 것이 없다.
forEach 는 단지 for 문 대신 사용하는 반복 method 이다.
즉, return하는 것이 없다는 것은
for문처럼 그저 반복적인 행위만 해줄 뿐,
for문 도는거랑 같은 개념이라고 생각하면 된다.
let startWithNames = []; // 빈 배열을 만들어주고 let names = ['a', 'ab', 'cbb', 'ada']; names.forEach(el => { if (el.startsWith('a')) { startWithNames.push(el); // 빈 배열에 넣어주기 } });
startWithName = [ 'a', 'ab', 'ada' ] 이 되었다.
문제풀면서 익히기
1. moreThan100 함수를 구현해 주세요.
- 숫자로 구성된 배열을 인자로 받습니다.
- 100 보다 크거나 같으면, true 를
- 100 보다 작으면 false 로 요소를 변경하여, 새로운 배열을 return 해주세요.
예를 들어,
nums(input)가
[100, 9, 30, 7]
이라면
return은
[true, false, false, false]✍🏻 문제풀기 ✍🏻
const moreThan100 = nums => { const arr = [] nums.map(number => { if (number >= 100) { number = true } else { number = false } arr.push(number) }) return arr }
2. formatDate 함수를 구현해 주세요.
- 날짜가 담긴 배열을 인자로 받습니다.
- 날짜의 data type은 string이며, 보내는 날짜 타입은 'YYYY-MM-DD' 입니다.
- 해당 날짜의 형식을 'YYYY년 MM월 DD일' 로 바꿔서, 새로운 배열을 return 해주세요.
예를 들어,
dates(input)가
['2019-03-21', '2019-04-21', '2019-05-21']
이라면
return은
['2019년 03월 21일', '2019년 04월 21일', '2019년 05월 21일']✍🏻 문제풀기 ✍🏻
const formatDate = dates => { dates.map((date, index) => { let year = date.split('-')[0] let month = date.split('-')[1] let day = date.split('-')[2] dates[index] = `${year}년 ${month}월 ${day}일` }) return dates; }
빙글빙글 반복문의 세계 머리가 어질어질하다.
하지만 알아가는 재미가 있다. 🙂🙂🙂🙂🙂
재미를 느끼고 있는 거 같아서 기분이 좋고 뿌듯하다.
더 많이 알아가야지👩🏻💻👩🏻💻👩🏻💻👩🏻💻
'프론트엔드 개발자가 될거야. > js' 카테고리의 다른 글
[instagram 클론코딩] input 창에 엔터치거나 "게시"누르면 댓글 추가 구현하기 (0) 2022.06.29 [Replit Javascript] 어려웠던 문제 총정리 (0) 2022.06.26 [TIL] Today I Learned : 개념공부 - string <-> number 변환 / 날짜 객체 (0) 2022.06.23 [TIL] Today I Learned : Srting - sliceCityFromAddress함수 (0) 2022.06.23 [TIL] Today I Learned : 배열 요소 추가, 제거 - divideArrayInHalf 함수 (0) 2022.06.23 - 숫자로 구성된 배열을 인자로 받습니다.