2012-08-10 65 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