我正在浏览Eloquent Javascript这本书,我正在做一个练习,我无法理解我做错了什么。 下面是正确计算平均值的代码(祖先是JSON对象):
function average(array) {
function plus(a, b) { return a + b; }
return array.reduce(plus) / array.length;
};
function age(p) { return p.died - p.born; };
function groupBy(array, action){
var groups = {};
array.forEach(function(individual){
var group = action(individual);
if (groups[group] == undefined)
groups[group] = [];
groups[group].push(individual);
});
return groups;
};
var centuries = groupBy(ancestry, function(person){
return Math.ceil(person.died / 100);
});
console.log(average(centuries[16].map(age)));
console.log(average(centuries[17].map(age)));
console.log(average(centuries[18].map(age)));
console.log(average(centuries[19].map(age)));
console.log(average(centuries[20].map(age)));
console.log(average(centuries[21].map(age)));
// → 16: 43.5
// 17: 51.2
// 18: 52.8
// 19: 54.8
// 20: 84.7
// 21: 94
哪一切都很好。但是,对于我的生活,我无法弄清楚如何编写最终不需要多个console.log调用的代码。这是我似乎最接近的,但我一直得到一个typeError,我不明白为什么。
for (century in centuries) {
console.log(average(century.map(age)));
};
为什么这不适用于循环工作? 提前谢谢!
答案 0 :(得分:5)
for..in循环将键值存储在您传递的变量中。
for (century in centuries) {
//here, century is the key (16, 17, etc)
//not the value of the entry in the array
console.log(average(centuries[century].map(age)));
}