Reputation: 1839
I'm doing an example of chart with chart JS. In the horizontal line, I'm showing four months to show the evolution of an indicator. I've an array of months composed this way. As you see each month with a key. My problem is that I don't' know how to loop when I arrive at the index n-3 = 0 to start again from the key 11
var date = new 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";
[month[n-3],month[n-2], month[n-1], month[n]]
@evolutionxbox I displayt he months like this 11 (december) 0 (january) 1 (February) 2. In code is illustrated like this month[n-3],month[n-2], month[n-1], month[n] . in this case n-3 = -1 i don't this key so i should return to 11.
So can anyone help me please. Thanks
Upvotes: 0
Views: 1337
Reputation: 413
Use the % Operator:
If you increment n just use n%12
. That way you start at 0 after 11+1=12.
In your case:
[month[(n-3)%12],month[(n-2)%12], month[(n-1)%12], month[n%12]]
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";
for(n =3;n< 24; n++){
console.log(month[(n-3)%12]+","+month[(n-2)%12]+","+month[(n-1)%12]+","+month[n%12])
}
Upvotes: 1