2012-08-10 67 views
2

虽然经历了Eloquent Javascript (Chapter 6),但还是有一个对Javascript中的高阶函数的引用。虽然第3章提供了一个例子,但我相信它可能会更简单一些,因为我仍然不完全理解这个概念。在搜索网页后,我似乎无法找到任何高级函数的简洁示例。javascript中一个简单的高阶函数的示例

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

回答

7

更高的功能是来自functional programming的概念。简而言之,更高级的功能是以另一个功能为参数的功能。在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遍历数组,并应用funcinit和数组的第一个元素,然后将结果绑定到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; 
} 
+0

感谢你们,这真的帮助我了解更多东西! – fakeguybrushthreepwood 2012-08-11 03:25:02