자바스크립트에서 함수는 일급 객체
함수를 변수에 할당할 수 있기 때문에, 함수를 배열의 요소나 객체의 속성값으로 저장할 수 있음
함수를 인자로 받을 수 있고, 함수의 형태로 리턴할 수 있는 함수
function doubleNum(func, num) {
let doubleArr = [];
return func(num); // 함수 doubleNum의 첫번째 인자 func에 함수가 들어오면, func는 doubleNum에 콜백 함수
}
function add(a) {
return function (b) {
return a + b
};
}
이 함수 add
는 인자 a를 받고 익명함수를 리턴, 리턴된 익명함수는 b를 받고 a와 b를 더한 값을 리턴, 리턴되는 익명 함수는 a에 대해 알고 있는 클로저
ECMA : "주어진 배열의 값들을 오름차순으로 접근해 callbackfn을 통해 true를 반환하는 요소를 기준으로 신규 배열을 만들어 반환"
arr.filter(callback(element[, index[, array]])[, thisArg])
callback : 각 요소에 대한 조건값
element : 처리할 현재 요소
index : 현재 인덱스
array : filter를 호출한 배열
thisArg : callback을 생행 할 때 this로 사용하는 값
예시)
const man = [ { name: 'YD', money: 500000 },
{ name: 'Bill', money: 400000 },
{ name: 'Andy', money: 300000 },
{ name: 'Roky', money: 200000 } ];
const rich = guys.filter(man => man.money > 300000);
console.log(rich); // [{name: 'YD', money: 500000}]
모든 값을 참 또는 거짓으로 분류해 원하는 조건을 만족하는 새로운 배열 반환
주어진 판별 함수를 만족하는 첫번째 요소의 값을 반환, 없다면 undefined 반환
const arrA = [5, 12, 4, 6, 3, 33];
const found = arrA.find(element => element > 10);
console.log(found); // 12
callbackFunction 을 실행한 결과를 가지고 새로운 배열을 만들 때 사용
array.map(callbackFunction(currenValue, index, array), thisArg)
currentValue : 배열 내 현재 값
index : 배열 내 현재 값의 인덱스
array : 현재 배열
thisArg : callbackFunction 내에서 this로 사용될 값
예시)
let numbers = [1, 2, 3, 4, 5]
let newNumbers = numbers.map(number => numbers * 2);
console.log(newNumbers) // [2,4,6,8,10]
var students = [
{id:1, name:"james"},
{id:2, name:"tim"},
{id:3, name:"john"},
{id:4, name:"brian"}
];
var names = students.map(student =>student.name);
console.log(names);
reduce sort some every
배열 각 요소에 callback함수를 적용할 수 있음
map과 비슷하지만 return 값이 없음
그래서기존 배열을 가공하여 평균, 합산 등을 구할 때는 forEach 사용 (속도)
array.forEach(callbackFunction(currnetValue, index, array), thisArg);
예시)
var objArr = [{name: '철수', age: 10},
{name: '영희', age: 10},
{name: '바둑이', age: 2}]
console.log(objArr.every((item)=> item.age>5)); // false
var objArr = [{name: '철수', age: 10},
{name: '영희', age: 10},
{name: '바둑이', age: 2}]
console.log(objArr.some((item)=> item.age>5)); //true