2

在阅读Eloquent Javascript(第 6 章)时,可以参考 Javascript 中的高阶函数。虽然第 3 章提供了一个示例,但我相信它可能会更简单一些,因为我还没有完全理解这个概念。在网上搜索后,我似乎找不到任何高阶函数的简洁示例。

我想在 Javascript 中看到一个基本/简单的高阶函数来解释这个概念。

4

1 回答 1

7

高级函数是函数式编程的概念。简而言之,高级函数是将另一个函数作为参数的函数。在javascript中,最近添加了一些更高的功能。

Array.prototype.reduce 
//With this function, we can do some funny things.
function sum(array){
    return array.reduce(function(a, b){ return a + b; }, 0);
}

所以,在上面的示例中,reduce是一个高阶函数,它以另一个函数,示例中的匿名函数作为参数。的签名reduce看起来像这样

reduce(func, init);
//func is a function takes two parameter and returns some value.
// init is the initial value which would be passed to func
//when calling reduce, some thing happen

//step 1.
[1, 2, 3, 4, 5].reduce(function(a, b){ return a + b }, 0);
//step 2.
[2, 3, 4, 5].reduce(function(a, b){ return a + b}, 0 + 1);
//step 3.
[3, 4, 5].reduce(function(a, b){ return a + b}, 0 + 1 + 2);
//...

如您所见,reduce迭代一个数组,并应用该数组的funcwithinit和第一个元素,然后将结果绑定到init.

另一个高阶函数是filter

Array.prototype.filter
//As the name indicates, it filter out some unwanted values from an Aarry. It also takes a function, which returns a boolean value, true for keeping this element.
[1, 2, 3, 4, 5].filter(function(ele){ return ele % 2 == 0; });

通过上面两个例子,我不得不说高阶函数不是那么容易理解,尤其是reduce. 但这并不复杂,具有更高阶的功能,实际上您的代码会更干净和可读。举filter个例子,它告诉人们它把所有奇数都扔掉了。

在这里,我想实现一个简单的filter函数来向您展示如何。

function filter(array, func){
    var output = [];
    for(var i = 0; i < array.length; i++){
      if(func(array[i])) output.push(array[i]);
    }
    return output;
}
于 2012-08-10T11:42:02.473 回答