You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从对象数组中返回寿命最长的人员对象?

解决找出寿命最长人员的问题

嘿,看起来你已经有了不错的开始,但确实还有几个关键点需要完善!咱们一步步来把这个函数搞定。

首先,先说说你现有代码里的小问题:

  • 你写了people[i].yearOfBirth - yearOfDeath,这顺序反啦!应该是去世年份减去出生年份才能得到寿命,不然会得到负数哦。
  • 没有考虑到有些人可能还在世(也就是没有yearOfDeath属性),这时候应该用当前年份来计算寿命。
  • 你只是在循环里计算了寿命,但没有把这些寿命做比较,也没有记录下寿命最长的那个人。

接下来咱们先完善你的for循环版本:

const findTheOldest = function(people) {
  // 初始化变量来保存当前找到的最长寿的人
  let oldestPerson = people[0];
  
  // 先写一个辅助函数,专门计算某个人的寿命
  const getAge = (person) => {
    const deathYear = person.yearOfDeath || new Date().getFullYear();
    return deathYear - person.yearOfBirth;
  };

  for (let i = 1; i < people.length; i++) {
    const currentPersonAge = getAge(people[i]);
    const oldestAge = getAge(oldestPerson);
    
    // 如果当前的人比记录的最长寿的人年龄大,就更新记录
    if (currentPersonAge > oldestAge) {
      oldestPerson = people[i];
    }
  }
  
  return oldestPerson;
};

const people = [
  { name: "Carly", yearOfBirth: 1942, yearOfDeath: 1970 },
  { name: "Ray", yearOfBirth: 1962, yearOfDeath: 2011 },
  { name: "Jane", yearOfBirth: 1912, yearOfDeath: 1941 },
];

// 测试一下,应该返回Ray
console.log(findTheOldest(people));

如果你喜欢更简洁的写法,数组的reduce方法简直是为这种场景量身定做的!它可以帮我们遍历数组并逐步累积出结果:

const findTheOldest = function(people) {
  const getAge = (person) => {
    const deathYear = person.yearOfDeath || new Date().getFullYear();
    return deathYear - person.yearOfBirth;
  };

  return people.reduce((oldest, current) => {
    const oldestAge = getAge(oldest);
    const currentAge = getAge(current);
    return currentAge > oldestAge ? current : oldest;
  }, people[0]);
};

咱们来解释一下核心逻辑:

  • getAge辅助函数:统一处理寿命计算,不管这个人是否在世,都能得到正确的年龄。
  • 不管是for循环还是reduce,核心都是逐个比较每个人的寿命,保留当前最长寿的对象。

测试你的例子,Ray的寿命是49岁(2011-1962),Carly是28岁,Jane是29岁,所以函数会正确返回Ray的对象。

内容的提问来源于stack exchange,提问作者I-Am-Programming

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 20:39:10