简体   繁体   English

如何遍历几个月

[英]how to loop over an array of months

I'm doing an example of chart with chart JS. 我正在用图表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 我的问题是,当我到达索引n-3 = 0以从键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] . @evolutionxbox我向他显示这样的月份:11(12月)0(1月)1(2月2)2。在代码中显示了本月[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. 在这种情况下,n-3 = -1我没有此键,所以我应该返回到11。

So can anyone help me please. 所以任何人都可以帮我。 Thanks 谢谢

Use the % Operator: If you increment n just use n%12 . 使用%运算符:如果增加n,则仅使用n%12 That way you start at 0 after 11+1=12. 这样,您可以在11 + 1 = 12之后从0开始。

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]) } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM