/**
* @param {Number} 想生成的月份
* @returns {Array} 月份数据
*/
function initMonthDays(currentMonth) {
let d = new Date()
d.setMonth(currentMonth - 1) // 设置当前月
d.setDate(1) // 设置为当月的1号
let monthList = []
let count = 0
let nextMonthCount = 0
for (let i = 0; i < 6; i++) {
let weekList = new Array(7);
if (i === 0) { // 当月第一周
for (let index = d.getDay() - 1; index < weekList.length; index++) {
weekList[index] = ++count
}
} else { // 剩余的周
for (let index = 0; index < weekList.length; index++) {
count++
if (count <= getDaysOfMonth(d.getMonth())) {
weekList[index] = count
} else { // 补充下个月的号数
weekList[index] = ++nextMonthCount
}
}
}
monthList.push(weekList);
}
// 补充上个月的号数
let preMonthDay = getDaysOfMonth(d.getMonth() - 1)
for (let index = d.getDay() - 2; index >= 0; index--) {
monthList[0][index] = preMonthDay--
}
return monthList
}
/**
* @param {Date} currentMonth 当前月份
* @returns {Number} 当前月的最后一天是多少号
*/
function getDaysOfMonth(currentMonth) {
let date = new Date()
date.setMonth(currentMonth + 1)
date.setDate(0)
return date.getDate()
}
const monthDaysArr = initMonthDays(3)
console.log(monthDaysArr);
网友评论