第一种方式:数组法
小时候,老师就比划拳头教我们:一月大,二月平,三月大,四月小,五月大,六月小,七月大,八月大,九月小,十月大,十一月小,十二月大。大代表31天,小代表30天,平就是28天,但有个特殊情况,闰年是有 2月是有29天的。那好,我们列个数组,用(月份-1)代表索引一一映射天数。
const getMonthDays1 = (year,month)=>{
const days = [31,28,31,30,31,30,31,31,30,31,30,31]
const isLeapYear = year % 400 ===0 ||(year % 4 === 0 && year % 100 !==0)
if(isLeapYear) days[1] = 29
return days[month -1]
}
console.log(getMonthDays1(2023,8)); // 31
console.log(getMonthDays1(2023,9)); // 30
console.log(getMonthDays1(2000,2)); // 29
console.log(getMonthDays1(2023,2)); // 28
第二种方式:内置函数
new Date()不传参,默认获取当前日期;这里要说说它的第三个参数, 0 或1 ,不传默认是 1,返回当月的第一天。如果置为 0 ,则返回当月的最后一天,正好给我们用。
const getMonthDays2 = (year,month)=>{
const days = new Date(year,month,0).getDate()
return days
}
console.log(getMonthDays1(2023,8)); // 31
console.log(getMonthDays1(2023,9)); // 30
console.log(getMonthDays1(2000,2)); // 29
console.log(getMonthDays1(2023,2)); // 28
结语
两种方法,我更倾向于第一种,给人就很神奇的感觉,有没有?纵使第二种方法简单粗暴,不假思索。