🙆♀️ 일급 객체(first-class citizen)의 세 가지 특징을 설명할 수 있다.
🙆♀️ 고차 함수(higher-order function)에 대해 설명할 수 있다.
함수는 다른 함수의 인자가 될 수 있다
함수가 함수를 리턴할 수 있다
🙆♀️ 배열 내장 고차함수 filter에 대해서 이해할 수 있다.
🙆♀️ filter에 대한 이해를 기반으로, 나머지 고차함수를 스스로 학습할 수 있다.
🙆♀️ forEach, find, filter, map, reduce, sort, some, every
let arr = [1,2,3]
arr.forEach((e) => console.log(e))
// 1
// 2
// 3
for문처럼 배열의요소 하나하나를 나타낸다.
let score = [4, 11, 2, 10, 3, 1];
/* 오류 */
score.sort(); // 1, 10, 11, 2, 3, 4
// ASCII 문자 순서로 정렬되어 숫자의 크기대로 나오지 않음
/* 정상 동작 */
score.sort(function(a, b) { // 오름차순
return a - b;
// 1, 2, 3, 4, 10, 11
});
score.sort(function(a, b) { // 내림차순
return b - a;
// 11, 10, 4, 3, 2, 1
});
배열 정렬
let items = [
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 },
{ name: 'And', value: 45 },
{ name: 'The', value: -12 },
{ name: 'Magnetic', value: 13 },
{ name: 'Zeros', value: 37 }
];
items.sort(function(a, b) {
if (a.name > b.name) {
return 1;
}
if (a.name < b.name) {
return -1;
}
// 이름이 같을 경우
return 0;
});
// 결과값
[
{name: "And", value: 45},
{name: "Edward", value: 21},
{name: "Magnetic", value: 13},
{name: "Sharpe", value: 37},
{name: "The", value: -12},
{name: "Zeros", value: 37}
]
const student = [
{ name : "재석", age : 21},
{ name : "광희", age : 25},
{ name : "형돈", age : 13},
{ name : "명수", age : 44}
]
/* 이름순으로 정렬 */
student.sort(function(a, b) { // 오름차순
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
// 광희, 명수, 재석, 형돈
});
student.sort(function(a, b) { // 내림차순
return a.name > b.name ? -1 : a.name < b.name ? 1 : 0;
// 형돈, 재석, 명수, 광희
});
/* 나이순으로 정렬 */
student.sort(function(a, b) { // 오름차순
return a["age"] - b["age"];
// 13, 21, 25, 44
});
student.sort(function(a, b) { // 내림차순
return b["age"] - a["age"];
// 44, 25, 21, 13
});
정렬할 Array의 요소의 개수가 2개 미만일 경우 ‘sort is not a function’ 오류가 난다.
const array = [1, 2, 3, 4, 5];
const even = (el) => el % 2 === 0;
console.log(array.some(even));
// true
배열 안의 어떤 요소라도 주어진 판별 함수를 통과하는지 테스트한다.
const isBelowThreshold = (el) => el < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
//true
every() 메서드는 배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트한다.
Boolean 값을 반환한다.
🙆♀️ 추상화(abstraction)에 대해 설명할 수 있다.
복잡한것을 압축해서 핵심만 뽑아낸 상태로 만드는것.
컴퓨터의 내부 구조에 대한 고민이 추상화로 해결되어서 생산성이 높아진다.
🙆♀️ 추상화의 관점에서 고차 함수가 갖는 이점에 대해 설명할 수 있다.
고차함수 = 함수를 전달받거나 함수를 리턴한다 = 사고(함수)에 대한 복잡한 로직은 감추어져 있다 = 사고 수준에서의 추상화
🙆♀️ 고차 함수를 활용하여 프로그램을 작성할 수 있다.
filter,map,reduce은 원본배열에 영향을 안주기때문에 메소드 사용한 결과를 변수에 담아줘야한다.
sort는 mutate
function getLongestElement4(arr) {
let longestEl = '';
return arr.reduce(function(acc, cur) {
if (cur.length > longestEl.length) {
longestEl = cur;
console.log('cur=',cur,cur.length)
} else {
longestEl = acc;
console.log('acc=',acc,acc.length)
}
console.log('longestEl=',longestEl,longestEl.length)
return longestEl;
},'');
getLongestElement4(['one','two','no'])
// cur= one 3
//longestEl= one 3
//acc= one 3
//longestEl= one 3
//acc= one 3
//longestEl= one 3
}
function getLongestElement5(arr) {
let longestEl = '';
return arr.reduce(function(acc, cur) {
if (cur.length > longestEl.length) {
longestEl = cur;
console.log('cur=',cur,cur.length)
} else {
longestEl = acc;
console.log('acc=',acc,acc.length)
}
console.log('longestEl=',longestEl,longestEl.length)
return longestEl.length;
},'');
}
getLongestElement5(['one','two','no'])
//cur= one 3
//longestEl= one 3
//acc= 3 undefined
//longestEl= 3 undefined
length를 왜 읽지 못하는가 궁금했는데 longestEl에는 문자열이아니라 숫자가 할당되어있기 때문이었다. 문자열의 length는 구할수 있지만 숫자는 length가 없다