所以我在做奥丁项目。其中一个练习现在暗示使用 reduce 方法。我有点卡在这里,我已经看过解决方案了。但是,如果我自己这样做,我真的不知道自己会犯什么样的错误。我得到的代码是这样的:
let findTheOldest = function(people) {
const oldestPerson = people.reduce((winner, person) => {
if ((person.yearOfDeath - person.yearOfBirth) > (winner.yearOfDeath - winner.yearOfBirth)) {
return person;
} else if ((person.yearOfDeath - person.yearOfBirth) <= (winner.yearOfDeath - winner.yearOfBirth)) {
return winner;
}
});
}
他们拥有的代码是:
const findTheOldest = function(array) {
return array.reduce((oldest, currentPerson) => {
const oldestAge = getAge(oldest.yearOfBirth, oldest.yearOfDeath)
const currentAge = getAge(currentPerson.yearOfBirth, currentPerson.yearOfDeath)
return oldestAge < currentAge ? currentPerson : oldest
})
}
const getAge = function(birth, death) {
if (!death) {
death = new Date().getFullYear();
}
return death - birth;
}
现在,我知道,如果我看一下,他们的代码会更加结构化。但我自己的“解决方案”是我最接近的一个。到现在为止,我正试图弄清楚有什么区别。我知道他们的代码最终会更好。它更加整洁,并且使用单独的变量来存储年龄更加清晰和清晰。然而,我和他们都以同样的方式返回“对象”。对于我应该能够通过的第一个测试用例,这就是我现在的想法。
也许我必须解释测试用例,第一个是根据 yearBirth 和 yearDeath 计算年龄来找到最年长的人。然后第二个测试用例应该解释一个还活着的人。第三个测试用例是活着的人实际上是最年长的人,所以它应该返回那个人。我现在只尝试第一个。
我得到的错误是“无法读取未定义的属性'名称'”。我认为这与解决方案试图访问我返回的对象的 name 属性有关。因为这是他们的提示:
您应该返回整个 person 对象,但测试大多只是检查以确保名称正确。
蝴蝶刀刀
明月笑刀无情
开满天机
相关分类