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

如何检测一维对象数组中是否包含青少年到百岁老人全年龄区间的记录

问题原因

  • 你计算好的年龄分组值没有写入原数组的ageBracket字段,allAges函数读取该字段时全为undefined,自然匹配不到预定义的分组,返回false
  • 缺少对≥100岁年龄的特殊处理逻辑,128岁计算得到的12不会自动转为10

修复后代码(无侵入式,不修改原数组)

var list = [
  { firstName: 'Harry', lastName: 'K.', country: 'Brazil', continent: 'Americas', age: 19, language: 'Python' },
  { firstName: 'Kseniya', lastName: 'T.', country: 'Belarus', continent: 'Europe', age: 29, language: 'JavaScript' },
  { firstName: 'Jing', lastName: 'X.', country: 'China', continent: 'Asia', age: 39, language: 'Ruby' },
  { firstName: 'Noa', lastName: 'A.', country: 'Israel', continent: 'Asia', age: 40, language: 'Ruby' },
  { firstName: 'Andrei', lastName: 'E.', country: 'Romania', continent: 'Europe', age: 59, language: 'C' },
  { firstName: 'Maria', lastName: 'S.', country: 'Peru', continent: 'Americas', age: 60, language: 'C' },
  { firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 75, language: 'Python' },
  { firstName: 'Chloe', lastName: 'K.', country: 'Guernsey', continent: 'Europe', age: 88, language: 'Ruby' },
  { firstName: 'Viktoria', lastName: 'W.', country: 'Bulgaria', continent: 'Europe', age: 98, language: 'PHP' },
  { firstName: 'Piotr', lastName: 'B.', country: 'Poland', continent: 'Europe', age: 128, language: 'JavaScript' }
];

function allAges(list) {
  const ageBrackets = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  return ageBrackets.every(bracket => {
    return list.some(item => {
      // 直接在匹配阶段计算分组,向下取整比parseInt更稳定
      const calculatedBracket = Math.floor(item.age / 10);
      // ≥100岁统一归类为分组10
      const finalBracket = calculatedBracket >= 10 ? 10 : calculatedBracket;
      return finalBracket === bracket;
    })
  })
}

console.log(allAges(list)); // 输出 true

若需要给原数组新增ageBracket字段的实现

// 提前处理所有元素的年龄分组
list.forEach(item => {
  const calculated = Math.floor(item.age / 10);
  item.ageBracket = calculated >= 10 ? 10 : calculated;
})

function allAges(list) {
  const ageBrackets = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  return ageBrackets.every(bracket => list.some(item => item.ageBracket === bracket))
}

console.log(allAges(list)); // 输出 true

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 11:24:03