繁体   English   中英

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

[英]Can't loop through JavaScript array using a for loop

我正在阅读《 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)));
};

为什么在循环中不起作用? 提前致谢!

Javascript中的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)));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM