有人可以用最简单的语言向我解释一下reduce方法到底是如何工作的吗?

问题描述 投票:0回答:1

我正在做 Odin 项目的练习,我需要使用 array.reduce 方法在对象数组(由不同年龄的人组成)中找到最年长的人。我通过查找尝试编码的解决方案来使其工作。我花了好几天的时间试图弄清楚在这种情况下,reduce 方法是如何工作的,但我不明白。

据我所知,函数通常会传递给带有两个参数的reduce方法,这两个参数始终代表1)数组的累积值和2)正在迭代的当前元素。但在我下面发布的代码中,参数似乎以一种用于比较数组中不同对象的方式工作。

我的问题是这样的:参数“oldest”显然代表数组中最年长的人。那是一个人。 一个元素。当该参数应该代表数组的accumulated值,从而将多个元素加在一起时,它是如何工作的?

我没有得到什么?

  const findTheOldest = function(array) { 
// Use reduce method to reduce the array by comparing current age with previous age
  return array.reduce((oldest, currentPerson) => {
    // oldestAge gets the age of the oldest person's year of death and birth
    const oldestAge = getAge(oldest.yearOfBirth, oldest.yearOfDeath);

    // currentAge gets the age of the current person's year of death and birth
    const currentAge = getAge(currentPerson.yearOfBirth, currentPerson.yearOfDeath);

    // return name if current age is older than the oldest age, else return current oldest age
    return oldestAge < currentAge ? currentPerson : oldest;
  });

};

const getAge = function(birth, death) {
 if (!death) {
death = new Date().getFullYear(); // return current year using Date()
}
return death - birth; // else just return age using death minus birth

console.log(findTheOldest(people).name); // Ray
javascript arrays methods
1个回答
0
投票

第一个值是上一次迭代返回的值。

当您使用

reduce
作为累加器时,您返回的值就是累加值,通常会给它一个表明这一点的名称。

在这种情况下,返回的值是先前值和当前值中较旧的值。

© www.soinside.com 2019 - 2024. All rights reserved.