我正在尝试运行一个脚本,该脚本根据预定的日期数组(公共假日)检查今天的日期。但是,我正在努力了解阵列设置。我已经使用单个日期在没有数组的情况下运行了脚本,但是没有获得如何将其转换为具有多个选项进行检查的数组的方法。
下面写的代码;
var today = new Date().getHours();
var daycheck = new Date().getDay();
var holidayArray = new Date('12/19/2019');
var todayDate = new Date();
if (holidayArray.setHours(0, 0, 0, 0) == todayDate.setHours(0, 0, 0, 0)) {
alert('This is outside of business hours (Public Holiday).');
window.history.back();
} else {
if (today <= 8 || today >= 17) {
alert('This is outside of business hours. General access is provided from 9am - 5pm Monday to Friday');
window.history.back();
}
else {
if (daycheck == 0 || daycheck == 6) {
alert('This is outside of business hours(weekend).');
window.history.back();
}
else {
if (confirm('It is currently within business hours during the week. You can now continue.')) {
window.location.href = "https://URL";
}
else { window.history.back() }
}
}
}
在向holidayArray
变量添加其他日期方面,我需要帮助,因为每次尝试进行操作都无法正常工作。
预先感谢
答案 0 :(得分:2)
在JavaScript中,您可以通过以下语法创建数组:var holidayArray = [new Date("12/19/2019"), new Date("12/20/2019"), new Date("12/21/2019")]
然后您必须遍历此数组,例如:
for (let holiday of holidayArray) {
// Place your IF statements in here and make your checks against the value "holiday". For example:
if (holiday.setHours(0,0,0,0) == todayDate.setHours(0,0,0,0)) {
alert("This is outside of business hours (Public Holiday).");
window.history.back();
}
}
这将依次遍历您的数组。 holiday
将代表数组中的每个值。
答案 1 :(得分:1)
Array.some()是您需要的:
https://www.w3schools.com/jsref/jsref_some.asp
将上面的代码放入checkDate函数中,然后复制下面的示例
function checkDate(d){
return d.setHours(0, 0, 0, 0) == todayDate.setHours(0, 0, 0, 0))
}
let isHoliday = holidayArray.some(checkDate);
还需要将holidayArray设置为Dates的数组,而不是Date