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

JavaScript使用map按条件返回数组对象值出现多余false结果如何解决

问题原因

map 方法会对数组的每一个元素执行回调,始终返回和原数组长度相同的新数组,不会自动过滤元素。
你使用的e.round === currentRound && new Date(e.at) <= roundDate && e.supplier_id遵循逻辑与运算规则:当所有条件都为真时,返回最后一个表达式的值也就是supplier_id;只要有一个条件为假,就直接返回假值,不符合条件的元素就会返回false存入结果数组,这就是你得到两个元素的原因。

修复方案

推荐先通过filter筛选符合条件的元素,再通过map提取对应的supplier_id即可:

const suppliersWhoSubmitBid = offers
  .filter(e => e.round === currentRound && new Date(e.at) <= roundDate)
  .map(e => e.supplier_id)

如果希望一次遍历完成,也可以用reduce实现:

const suppliersWhoSubmitBid = offers.reduce((result, current) => {
  if (current.round === currentRound && new Date(current.at) <= roundDate) {
    result.push(current.supplier_id)
  }
  return result
}, [])

两种写法最终得到的结果都和预期一致:[ '7a444fea780d90ddc7c35e09104c73b0' ]


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:54:04