数组循环javascript

时间:2016-12-23 10:29:04

标签: javascript html combobox

var categories = {
    "None":[{value:'1', text:'No category selected'}],
    "Monthly":[{value:'2', text:'January'},{value:'3', text:'February'},{value:'4', text:'March'},{value:'5', text:'April'},{value:'6', text:'May'},{value:'7', text:'June'},{value:'8', text:'July'},{value:'9', text:'August'},{value:'10', text:'September'},{value:'11', text:'October'},{value:'12', text:'November'},{value:'13', text:'December'}],
    "Yearly":[{value:'14', text:'2016'},{value:'15', text:'2017'},{value:'16', text:'2018'}],
}

是否可以在“年度”中进行循环播放。而不是逐个添加{value:'16', text:'2018'}或循环年份并在当前年份停止,然后在组合框中显示其文本。

1 个答案:

答案 0 :(得分:0)

我的评论主张如下:

var categories = {
    "None": [{value: '1', text: 'No category selected'}],

    "Monthly": [{
        value: '2',
        text: 'January'
    },
        {
            value: '3',
            text: 'February'
        },
        {
            value: '4',
            text: 'March'
        },
        {
            value: '5',
            text: 'April'
        },
        {
            value: '6',
            text: 'May'
        },
        {
            value: '7',
            text: 'June'
        },
        {
            value: '8',
            text: 'July'
        },
        {
            value: '9',
            text: 'August'
        },
        {
            value: '10',
            text: 'September'
        },
        {
            value: '11',
            text: 'October'
        },
        {
            value: '12',
            text: 'November'
        },
        {
            value: '13',
            text: 'December'
        }],

    "Yearly": []
};

function addYearlyCategoriesStartedFromGivenYearAndValue(startYear, startValue) {
    var currentYear = new Date().getFullYear();

    if (currentYear < startYear) {
        return; //exit to avoid endless loop
    }

    // assert that Yearly is array if not will set empty array 
    categories.Yearly = categories.Yearly || [];

    // below loop will push objects to array
    // starting from given startValue and startYear
    // until reaches currentYear (it will also be pushed)
    while (startYear <= currentYear) {
        categories.Yearly.push({
            // startValue++ post incrementation returns current value
            // and increments this variable for next get
            value: startValue++,
            text: startYear++
        });
    }
}

// create categories.Yearly array values
addYearlyCategoriesStartedFromGivenYearAndValue(2016, 14);