【发布时间】:2015-02-03 06:22:14
【问题描述】:
这个问题要求我们获取一组对象(每个对象都包含一个人的信息),将这些人按他们死在哪个世纪分组,然后得出一个人每个世纪的平均寿命。
我查看了教科书的解决方案,但我不明白为什么我的解决方案不能正常工作。
我能够生成一个由每个世纪的数组组成的对象,每个数组中的元素是我需要平均的年龄:
{16: [47, 40],
17: [40, 66, 45, 42, 63],
18: [41, 34, 28, 51, 67, 63, 45, 6, 43, 68, …],
19: [72, 45, 33, 65, 41, 73],
20: [73, 80, 90, 91, 92, 82],
21: [94]}
它们为我们提供了一个平均功能:
function average(array) {
function plus(a, b) { return a + b; }
return array.reduce(plus) / array.length;
}
然后我运行这段代码:
var obj = group(ancestry); //this is the object of arrays from above
for (var century in obj) {
console.log(century + ": " + average(century));
}
我应该得到这个:
// → 16: 43.5
// 17: 51.2
// 18: 52.8
// 19: 54.8
// 20: 84.7
// 21: 94
相反,我得到了这个错误:
TypeError: undefined is not a function (line 3 in function average)
called from line 26
//where line 3 is the third line in the average function
//and line 26 is the "console.log..." line from the last paragraph of code
非常感谢任何帮助!
【问题讨论】:
标签: javascript arrays javascript-objects