在浏览Eloquent Javascript(第6章)时,可以参考Javascript中的高阶函数.虽然第3章提供了一个例子,但我相信它可能会更简单,因为我仍然不完全理解这个概念.在搜索网络后,我似乎找不到任何高阶函数的简洁例子.
我想在Javascript中看到一个基本/简单的高阶函数来解释这个概念.
更高的功能是来自功能编程的概念.简而言之,更高的功能是将另一个功能作为参数的功能.在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);
}
Run Code Online (Sandbox Code Playgroud)
因此,在上面的示例中,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);
//...
Run Code Online (Sandbox Code Playgroud)
如您所见,reduce迭代一个数组,并应用该数组的funcwith init和first元素,然后将结果绑定到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; });
Run Code Online (Sandbox Code Playgroud)
通过以上两个例子,我不得不说高阶函数不是那么容易理解,特别是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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1476 次 |
| 最近记录: |