我正在使用图表 JS 做一个图表示例。在水平线上,我用四个月的时间来展示指标的演变。我有很多个月都是这样写的。正如您所见,每个月都有一把 key 。我的问题是,当我到达索引 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 我显示的月份是这样的 11(十二月) 0(一月) 1(二月) 2。在代码中如图所示本月[n-3],月份[n-2],月份[n-1 ],月[n]。在这种情况下 n-3 = -1 我没有这个键,所以我应该返回到 11。
请问有人可以帮助我吗?谢谢
最佳答案
使用%运算符:
如果您增加n,只需使用n%12
。这样你就可以在 11+1=12 之后从 0 开始。
就您而言:
[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])
}
关于javascript - 如何循环遍历几个月的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37920235/