头图
A structure that takes a function as a parameter, or a function as a return value, becomes a "higher-order function".

JavaScript parameters

parameter of value type

 function plusFive(number) {
  return number + 5;  
};
plusFive(3); // 8

Callback function type parameter

In JavaScript, functions can be passed as parameters to functions:

 const isEven = (n) => {
  return n % 2 == 0;
}

const isEven = (n) => {
  return n % 2 == 0;
}
 
let printMsg = (evenFunc, num) => {
  const isNumEven = evenFunc(num);
  console.log(`The number ${num} is an even number: ${isNumEven}.`)
}
 
// Pass in isEven as the callback function
printMsg(isEven, 4); 
// Prints: The number 4 is an even number: True.

Higher-Order Functions

When a function is passed as a parameter to a function, or as the return of a function, this structure is called a higher-order function.

.reduce()

The reduce function iterates over an array and returns an accumulated value.

 const arrayOfNumbers = [1, 2, 3, 4];
 
const sum = arrayOfNumbers.reduce((accumulator, currentValue) => {  
  return accumulator + currentValue;
});
 
console.log(sum); // 10

.forEach()

The forEach function passes in a function that traverses each element in the order of the array elements.

 const numbers = [28, 77, 45, 99, 27];
 
numbers.forEach(number => {  
  console.log(number);
});

.filter()

The filter function traverses each element in the order of the array elements, the callback function needs to return a boolean value, and the final return value of the function is an array.

 const randomNumbers = [4, 11, 42, 14, 39];
const filteredArray = randomNumbers.filter(n => {  
  return n > 5;
});

.map()

The map function traverses each element in the order of the array elements, returning a new array according to the logic of the callback function.

 const finalParticipants = ['Taylor', 'Donald', 'Don', 'Natasha', 'Bobby'];
 
// add string after each final participant
const announcements = finalParticipants.map(member => {
  return member + ' joined the contest.';
})
 
console.log(announcements);

来了老弟
508 声望31 粉丝

纸上得来终觉浅,绝知此事要躬行