試圖解決「歷史預期壽命」問題http://eloquentjavascript.net/05_higher_order.html。Javascript - 將函數傳遞給未定義的函數
從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),但那不是真的......有人能幫助我理解我不理解的東西嗎?謝謝。如果你在你的代碼,在這個片段中密切關注
如果groupOf = function(person){return Math.ceil(person.died/100);},那麼element = person? – user3164317