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

如何遍历JavaScript数组中的对象并计算年龄?

解决方法

1. 修复年龄计算逻辑

你的getAge函数用了剩余参数...people,但调用时直接传入整个数组,导致函数里的people变成了嵌套数组([[{...}, {...}, {...}]]),遍历的时候拿到的是整个数组而非单个对象。调整后可以直接遍历数组里的每个对象:

// 计算单个人的年龄,兼容未去世的情况(用当前年份代替死亡年份)
function calculateAge(person) {
  const deathYear = person.yearOfDeath || new Date().getFullYear();
  return deathYear - person.yearOfBirth;
}

// 遍历数组,输出每个人的年龄
function getAges(people) {
  for (const person of people) {
    const age = calculateAge(person);
    console.log(`${person.name} 的年龄是 ${age} 岁`);
  }
}

// 直接传入数组调用即可
getAges(people);

2. 实现findTheOldest函数

用数组的reduce方法可以高效找出年龄最大的人,逐个比较每个人的年龄,最终保留年龄最大的对象:

const findTheOldest = function(people) {
  return people.reduce((oldestPerson, currentPerson) => {
    const oldestAge = calculateAge(oldestPerson);
    const currentAge = calculateAge(currentPerson);
    return oldestAge > currentAge ? oldestPerson : currentPerson;
  });
};

// 测试调用,会输出Ray的对象(他活了49岁,是三人中最长的)
console.log(findTheOldest(people));

3. 完整整合代码

把所有逻辑整合到一起,功能更完整:

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

function calculateAge(person) {
  const deathYear = person.yearOfDeath || new Date().getFullYear();
  return deathYear - person.yearOfBirth;
}

function getAges(people) {
  for (const person of people) {
    const age = calculateAge(person);
    console.log(`${person.name} 的年龄是 ${age} 岁`);
  }
}

const findTheOldest = function(people) {
  return people.reduce((oldestPerson, currentPerson) => {
    const oldestAge = calculateAge(oldestPerson);
    const currentAge = calculateAge(currentPerson);
    return oldestAge > currentAge ? oldestPerson : currentPerson;
  });
};

// 执行测试
getAges(people);
console.log("\n年龄最大的人是:", findTheOldest(people));

核心要点

  • 遍历包含对象的数组很简单:用for...of直接遍历数组,每次迭代拿到的就是数组里的单个对象,直接访问对象属性(person.yearOfBirth这类)即可。
  • reduce是数组聚合常用方法,适合在数组中筛选符合条件的元素,这里用来逐个比较年龄大小。
  • 加入了对yearOfDeath不存在的兼容处理,让逻辑更健壮。

内容的提问来源于stack exchange,提问作者Weazzyefff

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 00:05:15