我有一个检查当前时间是否在工作时间之内的函数-目前,我仅使用布尔函数检查工作时间,夏令时和周末。
如何设置假期日期列表,并进行功能检查今天的当前日期是否是假期,如果是则返回true,否则返回false。
最好的方法是创建一个日期数组,
像这样?
var holidays = { // keys are formatted as month,day
"0,1": "Martin Luther King, Jr. Day",
"1,1": "President's Day",
"2,0": "Daylight Savings Time Begins",
"3,3": "Administrative Professionals Day",
"4,0": "Mother's Day",
"4,1": "Memorial Day",
"5,0": "Father's Day",
"6,0": "Parents Day",
"8,1": "Labor Day",
"8,0": "Gold Star Mothers Day",
"9,1": "Columbus Day",
"10,0": "Daylight Savings Time Ends",
"10,4": "Thanksgiving Day"
};
//or like this?
var holidays = ["Martin Luther King, Jr. Day": {
"day":"1",
"month":"0"
},
"President's Day": {
"day":"1",
"month":"1"
}];
然后检查
date.getMonth()
date.getDate()
等于列表中的一项,然后返回true,否则返回false
这样的事情行吗?
function checkHoliday(){
month = date.getMonth()
date = date.getDate()
for (var i=0; i < holidays.length ;i++){
if(holidays[i].day == date && holidays[i].month == month) {
return true
} else return false;
}
最佳答案
您不需要循环,因为您只需要构建密钥并检查其是否存在
而不是使用if / else返回true或false,您可以直接返回要检查的值
例
function checkHoliday(){
var month = date.getMonth();
var date = date.getDate();
return holidays.hasOwnProperty(month + ',' + date);
}