2015-05-06 34 views
0

試圖解決「歷史預期壽命」問題http://eloquentjavascript.net/05_higher_order.htmlJavascript - 將函數傳遞給未定義的函數

http://eloquentjavascript.net/code/#5.3解決辦法是這樣的:

function average(array) { 
    function plus(a, b) { return a + b; } 
    return array.reduce(plus)/array.length; 
} 

function groupBy(array, groupOf) { 
    var groups = {}; 
    array.forEach(function(element) { 
    if (groupOf(element) in groups) 
     groups[groupOf(element)].push(element); 
    else 
     groups[groupOf(element)] = [element]; 
    }); 
    return groups; 
} 

var byCentury = groupBy(ancestry, function(person) { 
    return Math.ceil(person.died/100); 
}); 

for (var century in byCentury) { 
    var ages = byCentury[century].map(function(person) { 
    return person.died - person.born; 
    }); 
    console.log(century + ": " + average(ages)); 
} 

// → 16: 43.5 
// 17: 51.2 
// 18: 52.8 
// 19: 54.8 
// 20: 84.7 
// 21: 94 

我的問題是圍繞groupOf(元素)。 這是怎麼回事?「元素」取值爲16,17,18,19,20或21(作爲函數(人){返回Math.ceil(person.died/100);})的結果。 a)groupOf(元素)是什麼樣的? groupOf從未定義。 b)在我看來,我可以用元素替換groupOf(element),但那不是真的......有人能幫助我理解我不理解的東西嗎?謝謝。如果你在你的代碼,在這個片段中密切關注

+0

如果groupOf = function(person){return Math.ceil(person.died/100);},那麼element = person? – user3164317

回答

0

groupOf is defined。它的一個參數在var byCentury = groupBy(ancestry, /* function goes here */);

由於所有的括號有點難以看到。這是一樣的做:

var myFunctionAsAParameter = function(person) { 
    return Math.ceil(person.died/100); 
} 

則...

var byCentury = groupBy(ancestry, myFunctionAsAParameter); 

myFunctionAsAParameter不執行,直到JavaScript和()看到它,你看到的情況是:groups[groupOf(element)].push(element);

所以在這種的情況下,它會執行幾次,每次與不同的人(由foreach循環確定)。

這是一個圍繞你的頭一陣掙扎,但它非常強大。函數可以將其他函數作爲參數。他們只會在添加()時被執行。如果需要,函數還可以返回其他函數。現在真的傷了你的頭。函數甚至可以返回並接受自己作爲參數(稱爲遞歸)。

+0

如果groupOf = function(person){return Math.ceil(person.died/100);},那麼element = person? – user3164317

0

var byCentury = groupBy(ancestry, function(person) { // element = function(person) {return Math.ceil(person.died/100);} 
    return Math.ceil(person.died/100); 
}); 

groupOf不過該功能,作爲第二個參數傳遞給GROUPBY

function(person) { // element = function(person) {return Math.ceil(person.died/100);} 
    return Math.ceil(person.died/100); 
} 

因爲功能只是在JavaScript對象,你也可以將它們傳遞給其他函數。

+0

如果groupOf = function(person){return Math.ceil(person.died/100);},那麼element = person? – user3164317

+0

這是正確的。 –