无法使用for循环遍历JavaScript数组

ben*_*rew 1 javascript object

我正在阅读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
Run Code Online (Sandbox Code Playgroud)

这一切都很好,很好.但是,对于我的生活,我无法弄清楚如何编写最终不需要多个console.log调用的代码.这是我似乎最接近的,但我一直得到一个typeError,我不明白为什么.

for (century in centuries) {
  console.log(average(century.map(age)));
};
Run Code Online (Sandbox Code Playgroud)

为什么这不适用于循环工作?提前致谢!

Sea*_*son 5

for..in循环在Javascript中存储您传递的变量中的键值.

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)));
}
Run Code Online (Sandbox Code Playgroud)