这是一个可以解决问题的函数(不使用Moment,而仅使用普通Javascript):
var getDaysArray = function(year, month) { var monthIndex = month - 1; # 0..11 instead of 1..12 var names = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ]; var date = new Date(year, monthIndex, 1); var result = []; while (date.getMonth() == monthIndex) { result.push(date.getDate() + "-" + names[date.getDay()]); date.setDate(date.getDate() + 1); } return result;}
例如:
js> getDaysArray(2012,2)["1-wed", "2-thu", "3-fri", "4-sat", "5-sun", "6-mon", "7-tue", "8-wed", "9-thu", "10-fri", "11-sat", "12-sun", "13-mon", "14-tue","15-wed", "16-thu", "17-fri", "18-sat", "19-sun", "20-mon", "21-tue", "22-wed", "23-thu", "24-fri", "25-sat", "26-sun", "27-mon", "28-tue","29-wed"]
ES2015 +版本:
const getDaysArray = (year, month) => { const monthIndex = month - 1 const names = Object.freeze( [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ]); const date = new Date(year, monthIndex, 1); const result = []; while (date.getMonth() == monthIndex) { result.push(`${date.getDate()}-${names[date.getDay()]}`); date.setDate(date.getDate() + 1); } return result;}
请注意,与问题中包含的示例输出不同,上述解决方案不会在10号之前将日期补零。使用ES2017 +可以轻松修复:
result.push(`${date.getDate()}`.padStart(2,'0') + `-${names[date.getDay()]}`);
在旧版本的JS中执行此 *** 作需要滚动您自己的零填充逻辑,这虽然不难,但也不是问题的重点。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)