javascript - 如何循环遍历几个月的数组

标签 javascript charts

我正在使用图表 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/

相关文章:

javascript - 使用 colorByPoint 时如何设置系列的图例符号颜色?

javascript - d3.time.format.multi 不是函数

javascript - 使用 AJAX 仅刷新一个 div

pdf - 如何以编程方式生成在图像顶部带有标签的维恩图图像?

c++ - 通过 C++ 将 QML 项作为图像复制到剪贴板

oracle - 从 Oracle 查询生成图表的选项

javascript - 如何在tinymce编辑器中允许一些自定义标签

javascript - 是否可以禁用输入类型电子邮件验证的默认行为

javascript - Contact Form 7 在发送电子邮件后不重定向

vba - 在崩溃时初始化图表对象VBA