[英]Javascript – passing a function to an undefined function
嘗試解決http://eloquentjavascript.net/05_higher_order.html上的“歷史預期壽命”問題。
來自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(element)。 這里發生了什么? “ element”的值為16,17,18,19,20或21(作為function(person)的結果{返回Math.ceil(person.died / 100);})。 a)groupOf(element)是什么樣的? groupOf從未定義。 b)在我看來,我可以用element代替groupOf(element),但事實並非如此……有人可以幫助我了解我不了解的內容嗎? 謝謝。
如果您仔細查看代碼中的此代碼段
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中的對象,因此您也可以將它們傳遞給其他函數。
groupOf 被定義。 它是var byCentury = groupBy(ancestry, /* function goes here */);
一個參數var byCentury = groupBy(ancestry, /* function goes here */);
由於所有括號,很難看清。 與執行操作相同:
var myFunctionAsAParameter = function(person) {
return Math.ceil(person.died / 100);
}
然后...
var byCentury = groupBy(ancestry, myFunctionAsAParameter);
在JavaScript用()
看到它之前, myFunctionAsAParameter
不會執行,您會在以下情況中看到它: groups[groupOf(element)].push(element);
因此,在這種情況下,它將每次被不同的人執行幾次(由foreach循環確定)。
纏住你的頭有點麻煩,但是它非常強大。 函數可以將其他函數用作參數。 僅當您添加()時,它們才會執行。 函數也可以根據需要返回其他函數。 現在真的傷到了你的頭。 函數甚至可以返回並接受自己作為參數(稱為遞歸)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.