方法一
function getMonthDay(year, month) { let days = new Date(year, month + 1, 0).getDate() return days }
new Date()第3個參數默認為1,就是每個月的1號,把它設置為0時, new Date()會返回上一個月的最后一天,然后通過getDate()方法得到天數
new Date()第二個參數設置為1就是2月
方法二
可以把每月的天數寫在數組中
再判斷時閏年還是平年確定2月分的天數
閏年條件:...
function getDays(year, month) { let days = [31,28,31,30,31,30,31,30,30,31,30,31] if ( (year % 4 ===0) && (year % 100 !==0 || year % 400 ===0) ) { days[1] = 29 }
return days[month] }