Array find per day React



我有一个时间表数组,我只想根据今天的日期在数组中显示1个数据。

{
schedule.map(s => {
let days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thurdsay', 'friday', 'saturday'];
let date = new Date();
let dayIndex = date.getDay();
let dayName = days[dayIndex]
let currentSchedule = schedule.find(s => s.days == dayName)
if(currentSchedule){
return <li className="list-group-item">{currentSchedule.day}: Open: {s.open} - Close: {s.close}</li>
}
})
}

电流输出

Satruday: opening: 10:00 AM PST - closing: 10:00 PM PST
Satruday: opening: 10:00 AM PST - closing: 10:00 PM PST
Satruday: opening: 10:00 AM PST - closing: 10:00 PM PST
Satruday: opening: 10:00 AM PST - closing: 10:00 PM PST
Satruday: opening: 10:00 AM PST - closing: 10:00 PM PST
Satruday: opening: 10:00 AM PST - closing: 10:00 PM PST
Satruday: opening: 10:00 AM PST - closing: 10:00 PM PST

我的期望输出是

例如今天是星期六,它只会输出
Satruday: opening: 10:00 AM PST - closing: 10:00 PM PST

Map()函数遍历数组的所有元素。您应该使用filter()函数来代替它。试试这段代码,应该能正常工作。

schedule.filter(s => {
let days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thurdsay', 'friday', 'saturday'];
let date = new Date();
let dayIndex = date.getDay();
let dayName = days[dayIndex];
let currentSchedule = schedule.find(s => s.days == dayName);
if(currentSchedule){
return <li className="list-group-item">{currentSchedule.day}: Open: {s.open} - Close: {s.close}</li>
}
})

但是最好在scheduler的定义中去掉重复的代码。

let days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thurdsay', 'friday', 'saturday'];
let date = new Date();
let dayIndex = date.getDay();
let dayName = days[dayIndex];

相关内容

  • 没有找到相关文章

最新更新