천진난만 코딩 스토리

2023.02.17) 항해 12일차 본문

TIL(Today I Learned)

2023.02.17) 항해 12일차

Wisdom_1104 2023. 2. 18. 10:56

자꾸만 헷갈리는 고차함수에 대해 다시 공부해 보았다.

 

1) map () / forEach ()

forEach와 map의 차이점은 리턴값이 있느냐, 없느냐이다.

forEach는 for문을 대체하여 내부에서 주어진 배열을 순회하고 리턴값이 없다.

그에 반해 map은 내부에 주어진 배열을 순회하여

콜백함수에서의 실행결과를 리턴값으로 이루어진 배열을 만들어 반환한다.

arrr.map ((currentValue, index, array) => {
}, thisArg)

currentValue : 처리할 현재 요소
index : 처리할 현재 요소의 인덱스
array : map()을 호출한 배열
thisArg : callback을 실행할 때 this로 사용되는 값

const array1 = [1, 4, 9, 16];

const map1 = array1.map(x => x * 2);

console.log(map1);   //Array [2, 8, 18, 32]

 

 

2) filter ()

주어진 배열을 순회하면서 콜백 함수의 반환값이 true에 해당하는 요소로만 구성된 새로운 배열을 생성하여 반환한다.

 

arrr.filter ((element, index, array) => {
}, thisArg)

element : 처리할 현재 요소
index : 처리할 현재 요소의 인덱스
array : filter()을 호출한 배열
thisArg : callback을 실행할 때 this로 사용되는 값

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);  //Array ["exuberant", "destruction", "present"]

 

3) splice()

 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경한다.

array.splice(start, deleteCount, item1, item2, (.....))

start : 배열의 변경을 시작할 인덱스
deleteCount : 배열에서 제거할 요소의 수
item1, item2, (.....) : 배열에 추가할 요소 (아무 요소도 지정하지 않으면 요소를 제거하기만 한다)

var number = ['one', 'two', 'three', 'four'];
var removed = number.splice(2, 1, 'five');

// number is ["one", "two", "four", "five"]
// removed is ["three"]

 

 

4) reduce ()

콜백 함수의 실행된 반환값을 전달받아 연산의 결과값을 반환한다.

arr.reduce((accumulator, currentValue, index, array) => {
}, initialValue);

accumulator : 콜백의 반환값을 누적하는 누산기
currentValue: 처리할 현재 요소
index : 처리할 현재 요소의 인덱스
array : reduce()를 호출한 배열
initialValue : callback의 최초 호출에서 첫 번째 인수에 제공하는 값 (초기값을 제공하지 않으면 배열의 첫 번째 요소를 사용)


const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue
);

console.log(sumWithInitial);   // 10

 

 

 

가장 많이 쓰이는 고차함수 위주로 공부해보았다.

이렇게 보니 또 이해가 되는 것 같지만 코드로 직접 작성해 보며 익숙해져야겠다.....

 

 

 

 

 

 

 

 

'TIL(Today I Learned)' 카테고리의 다른 글

2023.02.20) 항해 15일차  (0) 2023.02.20
2023.02.18) 항해 13일차  (0) 2023.02.20
2023.02.16) 항해 11일차  (0) 2023.02.17
2023.02.15) 항해 10일차  (0) 2023.02.16
2023. 02. 14) 항해 9일차  (0) 2023.02.15