簡體   English   中英

雄辯的JavaScript,第2版,練習5.3歷史人生預期

[英]Eloquent JavaScript, 2nd Edition, Exercise 5.3 Historical Life Expectancy

這個問題要求我們采取一系列對象(每個對象包含一個人的信息),將這些人分組到他們死亡的世紀,然后產生一個人每個世紀所經歷的平均年齡。

我查看了教科書解決方案,但我無法理解為什么我的解決方案不能正常工作。

我能夠為每個世紀生成一個由數組組成的對象,每個數組中的元素是我需要平均的年齡:

{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對數組中的每個元素執行一次回調函數,不包括數組中的空洞,接收四個參數:初始值(或前一個回調調用的值),當前元素的值,當前索引和正在進行迭代的數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM