高阶函数
如果一个函数操作其他函数,即将其他函数作为参数或将函数作为返回值,那么我们可以将其称为高阶函数。因为我们已经看到函数就是一个普通的值,那么高阶函数也就不是什么稀奇的概念了。高阶这个术语来源于数学,在数学当中,函数和值的概念有着严格的区分。
我们可以使用高阶函数对一系列操作和值进行抽象。高阶函数有多种表现形式。比如你可以使用高阶函数来新建另一些函数。
function greaterThan(n) {return m => m > n;}let greaterThan10 = greaterThan(10);console.log(greaterThan10(11));// → true
你也可以使用高阶函数来修改其他的函数。
function noisy(f) {return (...args) => {console.log("calling with", args);let result = f(...args);console.log("called with", args, ", returned", result);return result;};}noisy(Math.min)(3, 2, 1);// → calling with [3, 2, 1]// → called with [3, 2, 1] , returned 1
你甚至可以使用高阶函数来实现新的控制流。
function unless(test, then) {if (!test) then();}repeat(3, n => {unless(n % 2 == 1, () => {console.log(n, "is even");});});// → 0 is even// → 2 is even
有一个内置的数组方法,forEach,它提供了类似for/of循环的东西,作为一个高阶函数。
["A", "B"].forEach(l => console.log(l));// → A// → B
