簡體   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