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

TypeScript操作HashMap内数组值:移除重合元素失效问题

问题原因分析
  • Array.from(Map.values())返回的是二维数组:所有Map键对应的值会作为子元素组装为新数组,你示例中genericSlots仅存1个日期键,所以genericSlotsAsArray实际值为[ ["09:00","09:30",...] ],循环外层数组根本无法接触到内部的时段元素
  • 数组是引用类型,直接用===比较两个不同数组实例永远返回false,你需要对比的是两个数组内部的元素重合项,而非数组本身
  • 你修改的是从Map转出来的临时数组,完全没有改动genericSlots本身存储的时段数据,就算过滤逻辑正确也不会生效
修复后代码
checkForBookedSlots(date:string){
  let genericSlots = new Map<string,string[]>();
  let bookedSlots = new Map<string,string[]>();
  
  let bookedArray = ['09:00','11:00']
  let slotTimes = ["09:00", "09:30","10:00", "10:30", "11:00", "11:30", "12:00", "12:30","13:00","13:30", "14:00","14:30","15:00","15:30","16:00","16:30"]
  
  bookedSlots.set("09/10/2021",bookedArray)
  genericSlots.set(date,slotTimes)

  // 取出对应日期的时段数组,兼容键不存在的场景
  const targetGenericSlots = genericSlots.get(date) || [];
  const targetBookedSlots = bookedSlots.get(date) || [];
  // 转Set提升查询效率,数据量小也可以直接用Array.includes
  const bookedSet = new Set(targetBookedSlots);
  // 过滤掉已预约时段
  const filteredSlots = targetGenericSlots.filter(slot => !bookedSet.has(slot));
  // 可选:将过滤结果写回原Map
  genericSlots.set(date, filteredSlots);

  console.log('Generic Slots -> ', filteredSlots)
  console.log('Booked Slots -> ',  targetBookedSlots) 
}

运行后输出和你预期的结果完全一致。

内容的提问来源于stack exchange,提问作者D.Khumalo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:57:01