在JavaScript中为年,月,日生成表

时间:2018-01-18 17:53:44

标签: javascript arrays arraylist

$scope.generateTable = function(year) {
// use year and loop through each month to build an array dynamically
    this.year  = [];
    this.month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
// make an array for that starts with january and goes to December
    var month = moment().format('MMMM');
    for( i=0; i<=12; i++){
        this.month.push(i);
        console.log(month);
        }
}

如何生成一个可以循环遍历每个月的数组

当年度达到12月份时,年份自动递增, 例如,我需要打印出这样的列表:

2017
    {
      January: [
                "2017-01-01",
                "2017-01-02",
                "2017-01-03",
                ect..
               ],
     February: [
                "2017-02-01",
                "2017-02-02",
                "2017-03-03",
                etc..
               ]
        March: [
                "2017-03-01",
                "2017-03-02",`
                "2017-03-03",
                etc..
    }

2 个答案:

答案 0 :(得分:0)

不完全确定您到底在寻找什么,但似乎您正在使用moment.js。月份指数从0开始。所以这几个月的循环看起来像这样:

for (var i = 0; i < 12; i++) {
    months.push(moment().month(i));
}

检查these

答案 1 :(得分:0)

我怀疑你正在寻找这样的东西:

var generateTable = function (year) {
    // set an initial array of months, in chronological order (otherwise different trickery would be needed).
    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    // set some variable to an empty object (which we'll fill with a table and return).
    var range = {};
    const padLeft = (s) => s.toString().length === 1 ? '0' + s : s;
    // loop through the months
    months.forEach((month, index) => {
        var days = [],  // array for all days in the month
            i,          // basic iterator var
            d;          // temp var for a Date object
        for (i = 1; i < 32; i += 1) {
            // make a date using the index for the month.
            // if the months array weren't in chronological order,
            // we'd need to use another method to determine the month.
            d = new Date(year, index, i);
            if (d.getMonth() === index) {
                // if it's in the current month, add it
                days.push(`${d.getFullYear()}-${padLeft(d.getMonth() + 1)}-${padLeft(d.getDate())}`);
            }
            if (d.getMonth() !== index) {
                // if the date generated is actually outside the current month
                // as it would be in months like February (June, et. al.), then
                // end the loop by setting the iterator to an end condition.
                i = 32;
            }
        }
        // now that the days have been generated, add them to the return variable
        // keyed to the month name
        range[month] = days;
    });
    return range;
};

// and demo'd in action
console.log(generateTable(2018));