用While Loop &构建一个以年递增月份的函数;Momentjs

Building a function to increment months with years with While Loop & Momentjs

本文关键字:函数 Momentjs Loop While amp 一个以 构建      更新时间:2023-09-26

我正在尝试构建一个函数,允许我从当前月份增加x月份的数量。我使用while loopmomentjs,我能够增加月份,但增加年份有问题。下面是代码:

const generateMonths = (count) => {
let
  date = new Date(),
  month = date.getMonth(),
  year = date.getFullYear(),
  months = 12 + count,
  result = [];
while (month < months) {
 if (month >= 12) {
    let nextYear = year + 1;
    result.push(moment().month(month++).format("MMMM") + ' ' + nextYear);
  } else {
    result.push(moment().month(month++).format("MMMM") + ' - ' + year);
    }
  }
  return result;
};
console.log(generateMonths(24));

我得到的结果:

["August - 2016", "September - 2016", "October - 2016", "November - 2016", "December - 2016", "January 2017", "February 2017", "March 2017", "April 2017", "May 2017", "June 2017", "July 2017", "August 2017", "September 2017", "October 2017", "November 2017", "December 2017", "January 2017", "February 2017", "March 2017", "April 2017", "May 2017", "June 2017", "July 2017", "August 2017", "September 2017", "October 2017", "November 2017", "December 2017"]

年卡在2017,因为增量只发生一次,正确的方法是什么?谢谢!

我更改了您的代码,使其按预期工作。请注意,即使在12之后,变量month也会继续增加1,因此可以通过将month除以12并取结果的整数部分来计算第一年和新年之间的差值。

const generateMonths = (count) => {
let
  date = new Date(),
  month = date.getMonth(),
  year = date.getFullYear(),
  months = 12 + count,
  result = [];
while (month < months) {
    let newYear = Math.floor(month / 12) + year;
    result.push(moment().month(month++).format("MMMM") + ' ' + newYear);
  }
  return result;
};
console.log(generateMonths(24));
<script src="http://momentjs.com/downloads/moment.js"></script>

既然你在使用moment,你可以使用add方法来简化你的代码。

编辑:在Ilan Hasanov评论之后,我使用while而不是for来修复结果。

下面是一个工作示例:

const generateMonths = (count) => {
let
  date = moment(),
  month = date.month(),
  months = 12 + count,
  result = [];
  while (month < months) {
    result.push( date.format("MMMM YYYY") );
    date.add(1 ,'month');
    month++;
  }
  return result;
}
console.log(generateMonths(24));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>