[英]how to find a value in an array reactjs
I have a list of dates sent by the backend.我有一个后端发送的日期列表。 I need to work on that list to do a check.
我需要在该清单上进行检查。 If I have March dates in the list, I need to display the March events, and if I have April dates in the list, I need to display the April events and so on.
如果列表中有三月的日期,我需要显示三月的事件,如果列表中有四月的日期,我需要显示四月的事件等等。
However, I need to search the list by month and thus check what to display on the front end.但是,我需要按月搜索列表,从而检查要在前端显示的内容。
In my code that I provide below, events.date
would be the time to check to see if there is an event in March within the list.在我在下面提供的代码中,
events.date
将是检查列表中是否有 3 月份的事件的时间。
list:列表:
0: "2020-03-25"
1: "2020-03-26"
2: "2020-03-27"
3: "2020-03-28"
4: "2020-03-29"
5: "2020-03-30"
6: "2020-03-31"
7: "2020-04-01"
8: "2020-04-02"
9: "2020-04-13"
10: "2020-05-16"
11: "2020-06-27"
code:代码:
{
!events ? (
<Loading />
) : events.date === 0 ? (
[]
) : (
<>
<h1>Eventos de Março</h1>
<Month events={events} />
</>
);
}
You could use reducer get get a list of present months.您可以使用 reducer 获取当前月份的列表。 and then to check if there's the month you need.
然后检查是否有您需要的月份。
["2020-03-25",
"2020-03-26",
"2020-03-27",
"2020-03-28",
"2020-03-29",
"2020-03-30",
"2020-03-31",
"2020-04-01",
"2020-04-02",
"2020-04-13",
"2020-05-16",
"2020-06-27"].reduce(function (a, b) {
const d = new Date(b);
if (a.indexOf(d.getMonth() + 1) === -1) {
a.push(d.getMonth() + 1);
}
return a;
}, []).indexOf(4) !== -1; // <-- checking if April (4th month) is here.
Try something like尝试类似的东西
const datearr=events.map(dates=>{
let date = new Date(dates);
let monthno = date.getMonth();
if( monthno===2 ){
return date.getDay()
}
})
To handle this effectively, we'll need custom functionality.为了有效地处理这个问题,我们需要自定义功能。
Try this:尝试这个:
/* @param: month (type: number, range: 1-12)
* @returns: boolean (true/false)
*/
const EventDates = (month) => {
return ListOfDates.map(
// generate list of months
i => { let d = new Date(i); return d.getMonth() + 1; }
).includes(month); // check if a given month exists
};
console.log(EventDates(4))
// true
console.log(EventDates(1))
// false
You can then place this within the jsx
code:然后你可以把它放在
jsx
代码中:
- ) : events.date === 0 ? (
// replace with
+ ) : EventDates(month) ? (
// Either utilize `state` or `props` to change "month" parameter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.