如何在JavaScript中使用getDay()方法禁用日历多个星期几?
Great question! You’re already on the right track with disabling Sundays—expanding this to block multiple weekdays is straightforward using an array to list the days you want to disable.
Here’s how to modify your code:
First, remember that date.getDay() returns:
- 0 = Sunday
- 1 = Monday
- ...
- 6 = Saturday
Create an array of the day indices you want to disable, then check if the current date’s day is in that array using Array.includes() (or indexOf() for older browser support):
disabled: function (date) { // Define the weekdays you want to disable (0 = Sun, 6 = Sat) const disabledDays = [0, 6]; // Example: Disable Sunday and Saturday // Check if the current date's day is in the disabled array return disabledDays.includes(date.getDay()); }
Breakdown:
disabledDays: This array holds all the day numbers you want to block. You can adjust this to any combination—like[0, 2, 4]to disable Sunday, Tuesday, and Thursday.disabledDays.includes(date.getDay()): This checks if the current date’s weekday is in the disabled list. If it is, the function returnstrue(disabling the date), otherwisefalse.
For older browsers:
If you need to support browsers that don’t have Array.includes() (like IE), replace the check with indexOf():
return disabledDays.indexOf(date.getDay()) !== -1;
This approach keeps your code clean, scalable, and easy to update whenever you need to change which days are disabled.
内容的提问来源于stack exchange,提问作者Pamela

