2017-04-12 49 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对象检索她的记录中找到。