如何将日历无匹配事件时返回的undefined替换为null?
解决日历事件匹配时返回undefined的问题
当前你的代码中,使用events.find()匹配日期对应的事件时,找不到匹配项会返回undefined,导致后续遍历数组时出现异常。可以通过以下方式修改,将无匹配时的返回值改为null或空数组:
原相关代码
initialDays = initialDays.map((dates) => { return { date: format(dates, 'yyyy-MM-dd'), isCurrentMonth: isSameMonth(this.getNewDays, dates), isToday: isToday(dates), isSelected: isSameDay(dates, this.today), events: events.find((item) => { return item.datetime == format(dates, 'yyyy-MM-dd') }) } })
事件数组示例
let events = [{ id: 1, name: 'Date night', time: '6PM', datetime: '2022-10-10', href: '#' }, { id: 1, name: 'Date night', time: '8PM', datetime: '2022-10-10', href: '#' }, { id: 2, name: 'Date night', time: '6PM', datetime: '2022-10-12', href: '#' }, { id: 3, name: 'Date night', time: '6PM', datetime: '2022-10-13', href: '#' }]
解决方案
方案1:无匹配时返回null
使用空值合并运算符(??),仅当find()返回undefined或null时,替换为null:
initialDays = initialDays.map((dates) => { const formattedDate = format(dates, 'yyyy-MM-dd'); // 提取重复计算的日期,提升性能 return { date: formattedDate, isCurrentMonth: isSameMonth(this.getNewDays, dates), isToday: isToday(dates), isSelected: isSameDay(dates, this.today), events: events.find(item => item.datetime === formattedDate) ?? null } })
注:
??比||更安全,不会把0、空字符串等合法假值替换成null。
方案2:无匹配时返回空数组(更适合日历场景)
你的事件数组中存在同一天多个事件的情况(如2022-10-10有2条事件),find()仅会返回第一个匹配项,改用filter()可以获取当天所有事件,且无匹配时自动返回空数组:
initialDays = initialDays.map((dates) => { const formattedDate = format(dates, 'yyyy-MM-dd'); return { date: formattedDate, isCurrentMonth: isSameMonth(this.getNewDays, dates), isToday: isToday(dates), isSelected: isSameDay(dates, this.today), events: events.filter(item => item.datetime === formattedDate) } })
这种方式更符合日历展示需求,能完整显示当天所有事件,同时避免undefined问题。
内容的提问来源于stack exchange,提问作者DMantas
相关产品推荐
相关产品推荐

