亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Javascript,使用reduce數組方法

Javascript,使用reduce數組方法

HUX布斯 2022-07-21 10:37:47
所以我在做奧丁項目。其中一個練習現在暗示使用 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 對象,但測試大多只是檢查以確保名稱正確。
查看完整描述

3 回答

?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

在這種情況下,有可能沒有yearOfDeath(如果該人沒有死),您的代碼將檢索undefined并undefined - yearOfBirth給您NaN


任何比較NaN都將false因此您不會進入您的if分支,也不會進入您的else if分支。因此,您不會返回任何東西。如果你else if用一個簡單的替換它,else你會返回一些東西,但它可能是一個錯誤的結果,因為比較是錯誤的。


這就是為什么他們制作了一個函數來檢索當前年份,如果沒有yearOfDeath.


oldestPerson您還需要在函數末尾返回變量。


在您的代碼中,您可以添加如下內容(person.yearOfDeath || currentYear):


let findTheOldest = function(people) {

    const currentYear = new Date().getFullYear();

    const oldestPerson = people.reduce((winner, person) => {

        if (((person.yearOfDeath || currentYear) - person.yearOfBirth) > ((winner.yearOfDeath || currentYear) - winner.yearOfBirth)) {

            return person;

        } else if (((person.yearOfDeath || currentYear) - person.yearOfBirth) <= ((winner.yearOfDeath || currentYear) - winner.yearOfBirth)) {

            return winner;

        }

    });


    return oldestPerson;

}


const p1 = { yearOfBirth: 1990, yearOfDeath: 2015 }

const p2 = { yearOfBirth: 1990 } // Edge case: calculate his age with current year


console.log(findTheOldest([p1, p2]))

現在這段代碼很難閱讀,這就是為什么最好將它拆分成單獨的函數。



查看完整回答
反對 回復 2022-07-21
?
明月笑刀無情

TA貢獻1828條經驗 獲得超4個贊

我注意到的幾件事——

  • 當我們不打算重新分配變量時使用const(而不是)let

  • 使用初始值(第二個參數)reduce來防止數據集為空時程序崩潰

  • 使用復合結果會reduce阻止我們oldest在每次迭代中重新計算人的年齡

  • 使用默認值可防止空檢查、不必要的變量重新分配,并避免遇到NaN. 默認值還向程序員發出函數接受什么類型的數據的信號

const findTheOldest = (people = []) =>

  people.reduce

    ( ([ oldest, oldestAge ], person) => {

        const age = getAge(person) // only compute age of current person

        return age > oldestAge 

          ? [ person, age ]

          : [ oldest, oldestAge ]

      }

    , [ undefined, -Infinity ] // initial value

    )

    [0] // reduce returns [ <person>, <age> ], [0] gets the person out



const getAge = ({ yearOfBirth = 0, yearOfDeath = 0 }) =>

  yearOfDeath

    ? yearOfDeath - yearOfBirth

    : (new Date).getFullYear() - yearOfBirth


const peeps =

  [ { name: "Alice", yearOfBirth: 2000 }

  , { name: "Gertrude", yearOfBirth: 1910 }

  , { name: "Martha", yearOfBirth: 1900, yearOfDeath: 2006 }

  , { name: "Wanda", yearOfBirth: 1940 }

  ]


// works as expected

console.log(findTheOldest(peeps)) // { name: "Gertrude", ... }


// works when data source is empty

console.log(findTheOldest([])) // undefined


// works when data is missing!

console.log(findTheOldest()) // undefined


查看完整回答
反對 回復 2022-07-21
?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

試試這個:


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;

        }

    });

    return oldestPerson;

}


是一樣的,但我只是在函數末尾添加了 return oldPerson 。告訴我它是否有效


查看完整回答
反對 回復 2022-07-21
  • 3 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號