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

如何避免Array.map在回调条件不满足时返回数组包含undefined

你用map遍历数组时,所有元素都会被处理并返回对应值,当元素不满足item>60的判断条件时,函数没有显式返回值,默认返回undefined,所以最终结果中会存在大量无效的undefined项。

以下是两种符合你要求的实现方案,都不需要手动编写for循环做push操作:

方案1:map + filter 链式调用

写法直观易读,适合绝大多数普通场景:

const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];

const highAlarmsList = alarmsList
  .map((item, index) => item > 60 ? { value: item, index } : null)
  .filter(Boolean); // 自动过滤null、undefined等falsy值

console.log(highAlarmsList)
// 输出结果:[ { value: 61, index: 1 }, { value: 77, index: 2 }, { value: 85, index: 8 } ]

方案2:reduce 单次遍历实现

只需要遍历数组一次,性能更高,适合处理量级很大的数组:

const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];

const highAlarmsList = alarmsList.reduce((res, item, index) => {
    if(item > 60) {
        res.push({ value: item, index })
    }
    return res
}, []); // 初始值为空结果数组

console.log(highAlarmsList)
// 输出结果和方案1完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:15:03