使用While Loop& amp; amp; amp; amp; amp; amp; amp; amp; amp; Momentjs

时间:2016-08-18 22:22:48

标签: javascript while-loop ecmascript-6 momentjs

我正在尝试构建一个允许我从当月增加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,因为增量仅发生一次,这样做的正确方法是什么?谢谢!

2 个答案:

答案 0 :(得分:1)

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

&#13;
&#13;
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));
&#13;
<script src="http://momentjs.com/downloads/moment.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

由于您正在使用时刻,因此您可以使用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>