1

希望有人可以提供帮助。

我有以下函数来返回最后 6 个月份的名称(即 6 月、7 月、8 月等),但是,我无法弄清楚如何将每个返回的月份名称用作单独的变量。

我需要这个,以便我可以将每个月的名称输入到一个 sql 查询中,该查询填充了过去 6 个月的表。

非常感谢任何帮助。

function getMonths()
    {
        var today = new Date();             
        var month = 1;
        var currMonth = month-3;

        var monthArray = new Array("January","February","March","April","May","June",
                "July","August","September","October","November","December");

        var menuMonths = new Array();
        var count = 6;
        var buffer = 10;

        while(count >0)
        {           
            if (currMonth < 0)
                currMonth += 12;
            if (currMonth >=12 )
                currMonth -= 12;

            var month = monthArray[currMonth];
            menuMonths.push(month);

            currMonth = currMonth -1;
            count = count -1;
        }       
        return (menuMonths.reverse());
    } 


console.log (getMonths());
4

2 回答 2

1

您可以使用Array.slice()

小提琴 http://jsfiddle.net/BeNdErR/NF5Qm/1/

代码

var monthArray = new Array("January","February","March","April","May","June",
            "July","August","September","October","November","December");

var currMonth = 3; // the current month index, from 1 to 12
var firstMonth = currMonth - 6;

if(firstMonth < 0){ //for example if currMonth is January - 0
    var months = [];
    months.push(monthArray.slice(12 - Math.abs(firstMonth), 12));
    months.push(monthArray.slice(0, currMonth));
    alert(months);
}else{
    alert(monthArray.slice(firstMonth, currMonth))
}

作为输出,您仍然有一个数组,因此您可以按原样将其传递给 SQL 查询,例如 (SQLite):

tx.executeSql("SELECT * FROM tablename WHERE month = ? OR month = ? month = ? OR month = ? month = ? OR month = ?;", [slicedMonthArray], successCB, errorCB);

希望能帮助到你

于 2013-11-14T11:39:55.580 回答
0
var months = getMonths();

for(var i=0, len=months.length; i<len; i++){
   var currentMonth =  months[i];
   alert(currentMonth);
   //do whatever you want here;

}
于 2013-11-14T11:37:41.787 回答