为图表js创建动态标签时出现问题

时间:2019-01-31 07:35:12

标签: javascript

我通过提供month的范围为图表js创建动态标签。如果我按升序选择开始月份和结束月份会很好,但是在我选择开始月份=十二月并且结束月份= 3月的情况下却无法正常工作。

这是我的代码,

var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

var monthArr = [];

var monthn = ['December','March']; // here i give the lower and upper limit for the label 
for (var i = monthNames.indexOf(monthn[0]); i <= monthNames.indexOf(monthn[1]); i++) {
    monthArr.push(monthNames[i]);
}

return monthArr;

2 个答案:

答案 0 :(得分:0)

尝试验证两个月之间的索引

以下是您的代码示例,并做了很小的改动。

    var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

    var monthArr = [];

var monthn = ['December','March']; // here i give the lower and upper limit for the label 

    // make sure that StartMonth is smaller then Endmonth
    var startMonth = monthNames.indexOf(monthn[0]) <= monthNames.indexOf(monthn[1]) ? monthNames.indexOf(monthn[0]) : monthNames.indexOf(monthn[1]);

    // make sure that EndMonth is bigger then StartMonth
    var endMonth = monthNames.indexOf(monthn[0]) <= monthNames.indexOf(monthn[1]) ? monthNames.indexOf(monthn[1]) : monthNames.indexOf(monthn[0]);

    for (var i = startMonth; i <= endMonth; i++) {
        monthArr.push(monthNames[i]);
    }

    // Add the missing months
    if (startMonth -1 >0)
     {
       for (var i = 0; i <= startMonth -1; i++) {
        monthArr.push(monthNames[i]);
        }
     }

    console.log(monthArr)

答案 1 :(得分:0)

var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

var monthArr = [];
var monthn = ['December','March'];
if (monthNames.indexOf(monthn[1]) < monthNames.indexOf(monthn[0])) {
    monthNames.unshift(monthNames.splice(monthNames.indexOf(monthn[0]), 1)[0]);
    for (var i = monthNames.indexOf(monthn[0]); i <= diff; i++) {
        monthArr.push(monthNames[i]);
    }
} else {
    for (var i = monthNames.indexOf(monthn[0]); i <= monthNames.indexOf(monthn[1]); i++) {
        monthArr.push(monthNames[i]);
    }
}

return monthArr;