码:

months = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
  ];

currentMonth: String;

this.currentMonth = this.months[date.getMonth()];

nextMonth() {
    this.currentMonth = ...
}


我该如何构建nextMonth函数来更改currentMonth的值?例如,如果当前值是“ August”,我应该在函数中添加什么以使其值增加1,即将其值更改为“ September”?

最佳答案

您可以使用indexOf查找currentMonth并递增:

nextMonth = months[(months.indexOf(currentMonth) + 1) % 12];


最好将月份号简单地存储在currentMonth中。然后,您可以简单地增加currentMonth:

currentMonth = (currentMonth + 1) % 12;


并且仅在需要名称时引用months数组:

currentMonthName = months[currentMonth];

10-06 04:19