这是一个可以解决问题的函数(不使用 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 = (function() {
const names = Object.freeze([ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ]);
return (year, month) => {
const monthIndex = month - 1
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;
}
})();
作为旁注,您可以看到声明日期 const 并不能阻止我们对其进行变异(Object.freeze 也不会,用于使工作日名称数组不可变,对 Date 做任何事情) .我们在这里利用了可变性,但如果我们真的想要一个不可变的 Date 并使用在当前 Javascript 中强制执行该不变性的语言,我们必须go to some length。
另请注意,与问题中包含的示例输出不同,上述解决方案不会在 10 日之前补零日期。使用 ES2017+,这很容易修复:
result.push(`${date.getDate()}`.padStart(2,'0') + `-${names[date.getDay()]}`);
在旧版本的 JS 中执行此操作需要滚动您自己的零填充逻辑,这并不难,但也不是问题的真正重点。