这个问题要求我们获取一组对象(每个对象都包含有关一个人的信息),将这些人按他们死于哪个世纪进行分组,然后生成一个人在每个世纪的平均寿命。
我已经查看了教科书解决方案,但我不明白为什么我的解决方案不起作用。
我能够为每个世纪生成一个由数组组成的对象,每个数组中的元素是我需要平均的年龄:
{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
任何帮助将不胜感激!
编辑:哦,我以前没有注意到它,但你正在使用for..in 循环,然后对键而不是值进行操作。
按原样制作循环:
for (var century in obj) {
console.log(century + ": " + average(obj[century]));
}
阅读 Array.prototype.reduce 函数。reduce函数期望回调作为第一个参数 - 一个操作并返回可变对象(对象或数组)的函数。
从 MDN 链接本身:
reduce 对数组中存在的每个元素执行一次回调函数,不包括数组中的漏洞,接收四个参数:初始值(或来自上一次回调调用的值)、当前元素的值、当前索引和发生迭代的数组。