猿问

Javascript,使用reduce数组方法

所以我在做奥丁项目。其中一个练习现在暗示使用 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 对象,但测试大多只是检查以确保名称正确。


HUX布斯
浏览 171回答 3
3回答

蝴蝶刀刀

在这种情况下,有可能没有yearOfDeath(如果该人没有死),您的代码将检索undefined并undefined - yearOfBirth给您NaN任何比较NaN都将false因此您不会进入您的if分支,也不会进入您的else if分支。因此,您不会返回任何东西。如果你else if用一个简单的替换它,else你会返回一些东西,但它可能是一个错误的结果,因为比较是错误的。这就是为什么他们制作了一个函数来检索当前年份,如果没有yearOfDeath.oldestPerson您还需要在函数末尾返回变量。在您的代码中,您可以添加如下内容(person.yearOfDeath || currentYear):let findTheOldest = function(people) {&nbsp; &nbsp; const currentYear = new Date().getFullYear();&nbsp; &nbsp; const oldestPerson = people.reduce((winner, person) => {&nbsp; &nbsp; &nbsp; &nbsp; if (((person.yearOfDeath || currentYear) - person.yearOfBirth) > ((winner.yearOfDeath || currentYear) - winner.yearOfBirth)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return person;&nbsp; &nbsp; &nbsp; &nbsp; } else if (((person.yearOfDeath || currentYear) - person.yearOfBirth) <= ((winner.yearOfDeath || currentYear) - winner.yearOfBirth)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return winner;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; return oldestPerson;}const p1 = { yearOfBirth: 1990, yearOfDeath: 2015 }const p2 = { yearOfBirth: 1990 } // Edge case: calculate his age with current yearconsole.log(findTheOldest([p1, p2]))现在这段代码很难阅读,这就是为什么最好将它拆分成单独的函数。

明月笑刀无情

我注意到的几件事——当我们不打算重新分配变量时使用const(而不是)let使用初始值(第二个参数)reduce来防止数据集为空时程序崩溃使用复合结果会reduce阻止我们oldest在每次迭代中重新计算人的年龄使用默认值可防止空检查、不必要的变量重新分配,并避免遇到NaN.&nbsp;默认值还向程序员发出函数接受什么类型的数据的信号const findTheOldest = (people = []) =>&nbsp; people.reduce&nbsp; &nbsp; ( ([ oldest, oldestAge ], person) => {&nbsp; &nbsp; &nbsp; &nbsp; const age = getAge(person) // only compute age of current person&nbsp; &nbsp; &nbsp; &nbsp; return age > oldestAge&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ? [ person, age ]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; : [ oldest, oldestAge ]&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; , [ undefined, -Infinity ] // initial value&nbsp; &nbsp; )&nbsp; &nbsp; [0] // reduce returns [ <person>, <age> ], [0] gets the person outconst getAge = ({ yearOfBirth = 0, yearOfDeath = 0 }) =>&nbsp; yearOfDeath&nbsp; &nbsp; ? yearOfDeath - yearOfBirth&nbsp; &nbsp; : (new Date).getFullYear() - yearOfBirthconst peeps =&nbsp; [ { name: "Alice", yearOfBirth: 2000 }&nbsp; , { name: "Gertrude", yearOfBirth: 1910 }&nbsp; , { name: "Martha", yearOfBirth: 1900, yearOfDeath: 2006 }&nbsp; , { name: "Wanda", yearOfBirth: 1940 }&nbsp; ]// works as expectedconsole.log(findTheOldest(peeps)) // { name: "Gertrude", ... }// works when data source is emptyconsole.log(findTheOldest([])) // undefined// works when data is missing!console.log(findTheOldest()) // undefined

开满天机

试试这个:let findTheOldest = function(people) {&nbsp; &nbsp; const oldestPerson = people.reduce((winner, person) => {&nbsp; &nbsp; &nbsp; &nbsp; if ((person.yearOfDeath - person.yearOfBirth) > (winner.yearOfDeath - winner.yearOfBirth)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return person;&nbsp; &nbsp; &nbsp; &nbsp; } else if ((person.yearOfDeath - person.yearOfBirth) <= (winner.yearOfDeath - winner.yearOfBirth)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return winner;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; return oldestPerson;}是一样的,但我只是在函数末尾添加了 return oldPerson 。告诉我它是否有效
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答