2017-04-12 48 views
0

我有一個問題,因爲我的代碼返回不同的結果比解決方案代碼。我發現不同之處在於過濾功能。雄辯的JavaScript 5.2母子

鏈接excersise:http://eloquentjavascript.net/code/#5.2

我的過濾功能:

ancestry.filter(function(p) { return p.mother != null; }) 

回報33的結果,而從溶液過濾函數只返回17:

ancestry.filter(function(person) { return byName[person.mother] != null;}) 

哪一個是正確的?爲什麼第二個函數返回不同的結果?

第二個問題:

我不知道怎麼拉出生日期映射功能的母親。

function ageDiff(p) { return p.born - p.mother.born } //p.mother.born doesn't work 

感謝,KK

+0

與你問的無關,'return(p.mother!= null)? true:false;'可以簡化爲'return(p.mother!= null)'。 – nnnnnn

+0

謝謝:)代碼已更新。 – Kamil

+0

_「爲什麼第二個函數返回不同的結果?」_因爲'p.mother!= null'與'byName [person.mother]!= null'不一樣 – Andreas

回答

1

你得到不同的結果的原因是因爲你沒有測試同樣的事情。

在你的問題中未顯示此代碼:

var byName = {}; 
ancestry.forEach(function(person) { 
    byName[person.name] = person; 
}); 

...這與每個人的陣列,這樣你可以查找該人與byName["person's name here"]在屬性填充byName對象。

考慮到這一點

所以,你的代碼:

ancestry.filter(function(p) { return p.mother != null; }) 

......說來過濾ancestry陣列和只保留有一個mother屬性不是null元素。

官方的答案代碼:

ancestry.filter(function(person) { return byName[person.mother] != null;}) 

......說來過濾ancestry陣列並保持其指定.mother存在byName對象中的元素。也就是說,那些指定的母親自己排列在ancestry陣列中的元素 - 並非全部都是:Emma de Milliano是一個母親不是空的人,但在陣列中沒有自己的入場者的例子。 (也就是說,它正在測試!= null事實是有點誤導,因爲事實上byName有一個null值沒有屬性:什麼!= null測試確實在這種情況下測試!= undefined,因爲!=運營商認爲nullundefined相等。 )

我不知道如何拉母親出生日期的映射功能。

母親的方式,與byName[p.mother]byName對象檢索她的記錄中找到。