你很亲密。正如 Jaromanda X 建议的那样,从 1 开始并一直持续到月份变化(并且不要忘记将变量保持在本地)。您每次都需要复制日期:
function Ctrl($scope) {
$scope.dates = [];
var d = new Date(),
i = 1,
m = d.getMonth();
// Set date to start of month
d.setDate(i);
// Store the current month and keep going until it changes
while (d.getMonth() == m) {
// Store dates as a string (format however you wish)
$scope.dates.push('' + d);
// Or store dates as Date objects
$scope.dates.push(new Date(+d));
// Increment date
d.setDate(++i);
}
// return something?
}
编辑
允许输入月份(也是 do 而不是 for 循环的示例):
// Use calendar month number for month, i.e. 1=jan, 2=feb, etc.
function Ctrl($scope, month) {
$scope.dates = [];
var d = new Date();
d.setMonth(month - 1, 1);
do {
$scope.dates.push('' + d);
d.setDate(d.getDate() + 1);
} while (d.getDate() != 1)
}
或允许输入月份和年份,默认为当前月份和年份:
function Ctrl($scope, month, year) {
$scope.dates = [];
var d = new Date();
d.setFullYear(+year || d.getFullYear(), month - 1 || d.getMonth(), 1);
do {
$scope.dates.push('' + d);
d.setDate(d.getDate() + 1);
} while (d.getDate() != 1)
}