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

自定义filterByPHA函数筛选数组后调用Math.max遇TypeError求助

问题原因

你的filterByPHA函数仅执行打印操作,没有返回任何数据(JavaScript中函数默认返回undefined)。当你尝试对filterByPHA(neowise)调用.map()时,相当于在undefined上调用方法,这就触发了Cannot read properties of undefined (reading 'map')错误。

解决方案

方案1:修改原函数,让它同时返回筛选后的数组

调整filterByPHA,在打印的同时收集符合条件的对象并返回:

function filterByPHA(neowise) {
  const phaNeos = [];
  for (let i = 0; i < neowise.length; i++) {
    let neo = neowise[i];
    if (neo.pha === true) {
      console.log(`${neo.designation}: ${neo.orbit_class}`);
      phaNeos.push(neo);
    }
  }
  return phaNeos;
}

// 计算最大值(先判断数组是否为空,避免Math.max空参数返回-Infinity)
const phaNeos = filterByPHA(neowise);
const maxMOID = phaNeos.length > 0 ? Math.max(...phaNeos.map(x => x.moid_au)) : 0;
console.log(maxMOID);

方案2:直接用数组原生方法(更简洁)

利用数组的filter方法完成筛选,同时保留打印逻辑,再计算最大值:

// 筛选并打印符合条件的对象
const phaNeos = neowise.filter(neo => {
  if (neo.pha === true) {
    console.log(`${neo.designation}: ${neo.orbit_class}`);
    return true;
  }
  return false;
});

// 计算最大值
const maxMOID = phaNeos.length ? Math.max(...phaNeos.map(x => x.moid_au)) : 0;
console.log(maxMOID);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 11:21:19