
고차함수(High order Function)란 함수를 함수의 인자로 전달받거나
return 값으로 함수를 return 하는 함수를 말한다.
배열에서 이러한 고차함수를 이용하여 복잡한 코드를 단순화 할 수 있다.
고차함수에 들어오는 인자중 this는 콜백함수를 실행할때 this로 사용할 값이다.
let arr = ["a","b","c"];
arr.forEach( (item,_,array) => {
console.log(`${item} is in ${array}`);
});
/*a is in a,b,c
b is in a,b,c
c is in a,b,c
*/
callback함수에서 중간 매개변수를 쓰지 않으면 _ 를쓰면된다.
let users = [ // 배열속에 객체가 있을 때
{id: 1, name: "John"},
{id: 2, name: "Pete"},
{id: 3, name: "Mary"}
];
//
let users = users.find(item => item.id==1);
console.log(users); //{id: 1, name: "John"} 반환
let users = [ // 배열속에 객체가 있을 때
{id: 1, name: "John"},
{id: 2, name: "Pete"},
{id: 3, name: "Mary"}
];
let users = users.findIndex(item => item.id==2);
console.log(users); //1
let res= [2,5,10,1,4].some(item => item>5);
console.log(res); // true
let res= [2,5,10,1,4].evert(item => item>5);
console.log(res); // false
const arr= [1,2,3,4,5];
const result = arr.filter(item => item %2); // return이 true(1)만 필터링
console.log(result); // [1,3,5]
function Prefixer(prefix) {
this.prefix = prefix;
}
Prefixer.prototype.prefixArray = function (arr) {
return arr.map(x =>this.prefix+x, this);
// this는 pre객체
};
const pre = new Prefixer('-webkit-');
const preArr = pre.prefixArray(['linear-gradient', 'border-radius']);
console.log(preArr);
// [ '-webkit-linear-gradient', '-webkit-border-radius' ]
콜백함수에서 this를 써야 할 때 map의 두번째 인자에 this를 추가하지 않으면 this는 브라우저 전역 객체(window)를 가리킨다.
const nums = [1, 2, 3, 4, 5];
const result = nums.flatMap((item) => [1, 2]);
console.log(result);
/*[
1, 2, 1, 2, 1,
2, 1, 2, 1, 2
]
*/
arr.sort([compareFunction]);
const b= [1,2,100,10,3];
b.sort();
console.log(b); // [1,10,100,2,3] (정렬이 제대로 되지 않음)
b.sort( (a,b)=> a-b); // 비교함수 설정
// a-b<0 오름차순
// a-b>0 내림차순
console.log(b); // 1, 2, 3, 10, 100 ]
const result = [1, 2, 3, 4, 5].reduce((sum, value) => (sum += value), 0);
console.log(result); // 10