我试图向后循环11个月。基本上,我有一个当月(2019年9月),我想回溯11个月,以至2018年10月结束。我查看了很多代码片段,但没有一个片段涵盖了整个“重新开始”部分。重点是将这几个月推入下拉菜单。因此具有当前月份和前11个月。

我已经尝试过此代码段。它只是前进。当我将其设置为向后退时,就会出现无尽的循环,这会杀死我的Chrome。

这是我到目前为止的内容:

var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];
var d = new Date();
console.log(d.getMonth() + " is the index");

var index = monthNames[d.getMonth()];
console.log(index + ' is the month');
let monthIndex = monthNames.indexOf(index);
var n = 11

var result = [];

for (var i = monthIndex, len = monthNames.length; i <= monthIndex + n; i++) {
    result.push(monthNames[(i + len) % len]);
}


console.log(result.join(", "));



当我希望它从9月开始,然后向后延伸到10月,它在几个月后向前发展。

任何帮助表示赞赏。谢谢!

最佳答案

与上述建议相差无几,但较容易理解

var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];
var currentDate = new Date();
var currentMonthIndex = currentDate.getMonth();
var result = [];
var monthLength = 12;

for (var i = currentMonthIndex; i < monthLength; i--) {
  result.push(monthNames[i]);

  if (result.length === monthLength) {
    break;
  }

  if (i === 0) {
    i = monthLength;
  }
}


console.log(result.join(", "));

关于javascript - 如何向后循环遍历字符串数组x次,并在到达终点时重新开始?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57762658/

10-11 13:01