<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>js根据月份获取天数和对应的星期</title> </head> <body> </body> <script> var date = new Date(); var year = date.getFullYear(); //获取完整的年份(4位) var month = date.getMonth() + 1; //获取当前月份(0-11,0代表1月) var dataList = [] monthDays(year, month) //传入参数年和月 function monthDays(year, month) { var stratDate = new Date(year, month - 1, 1), endData = new Date(year, month, 1); var days = (endData - stratDate) / (1000 * 60 * 60 * 24); var list = [] for (var i = 1; i <= days; i++) { const day = i; const date = month + '-' + day; const week = new Date(month + '/' + i + '/' + year).getDay() == 0 ? '周日' : new Date(month + '/' + i + '/' + year) .getDay() == 1 ? '周一' : new Date(month + '/' + i + '/' + year).getDay() == 2 ? '周二' : new Date(month + '/' + i + '/' + year).getDay() == 3 ? '周三' : new Date(month + '/' + i + '/' + year).getDay() == 4 ? '周四' : new Date(month + '/' + i + '/' + year).getDay() == 5 ? '周五' : new Date(month + '/' + i + '/' + year) .getDay() == 6 ? '周六' : ''; list.push({ date, week, day, }) } dataList = list } console.log(year, month, dataList, 'dataList') </script> </html>