You get this undefined because month[-1]both month[-2]areundefined
You need to actually manipulate the dates in the date object, and not just get the date from the index.
Use this method to get the date of the last month.
function getPrevMonth(date) {
date.setMonth(date.getMonth() - 1);
return date;
}
, .
Demo
function getPrevMonth(date) {
date.setMonth(date.getMonth() - 1);
return date;
}
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var cur_month = new Date();
var cur_month_now = month[cur_month.getMonth()];
var pre_month_1 = month[getPrevMonth(cur_month).getMonth()];
var pre_month_2 = month[getPrevMonth(cur_month).getMonth()];
var pre_month_3 = month[getPrevMonth(cur_month).getMonth()];
var pre_month_4 = month[getPrevMonth(cur_month).getMonth()];
var pre_month_5 = month[getPrevMonth(cur_month).getMonth()];
document.getElementById("cur_month").innerHTML = cur_month_now;
document.getElementById("pre_month_1").innerHTML = pre_month_1;
document.getElementById("pre_month_2").innerHTML = pre_month_2;
document.getElementById("pre_month_3").innerHTML = pre_month_3;
document.getElementById("pre_month_4").innerHTML = pre_month_4;
document.getElementById("pre_month_5").innerHTML = pre_month_5;
<div class="dropdown">
<button class="btn btn-danger dropdown-toggle" type="button" data-toggle="dropdown">Select Month
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li>
<a href="#" id="cur_month"></a>
</li>
<li>
<a href="#" id="pre_month_1"></a>
</li>
<li>
<a href="#" id="pre_month_2"></a>
</li>
<li>
<a href="#" id="pre_month_3"></a>
</li>
<li>
<a href="#" id="pre_month_4"></a>
</li>
<li>
<a href="#" id="pre_month_5"></a>
</li>
</ul>
</div>
Hide result