JS之First-Class Functions

First-Class Functions(头等函数)

  • 函数享有与变量同等的待遇

    • 可被赋值给变量、数列元素和对象属性
    • 可作为参数传递给其他函数
    • 可被函数作为返回值
  • 允许声明高阶函数(higher-order function)

    • 接受函数作为参数或者返回函数的函数为高阶函数,如map(), filter(), reduce()
  • map()函数

const arr = [0,1,2,3];
function add(num) {
return num+=1; //or ++num, or else num++ returns num before adding 1
}

arr.map(a => add(a));         //[1,2,3,4]
  • filter()函数
const arr = [0,1,2,3];
function isGreaterThanOne(num) {
return num > 1;
}
console.log(isGreaterThanOne(2));                 // true
arr.filter(a => isGreaterThanOne(a));              // [2,3]
  • reduce()函数
const arr = [0,1,2,3];
const reducer = function(a,b) {
return a + b;
};
console.log(reducer(1,2));      // 3
arr.reduce(reducer,10);         //16

你可能感兴趣的:(JS之First-Class Functions)