gpt4 book ai didi

javascript - 使用 While Loop 和 Momentjs 构建一个以年为单位递增月份的函数

转载 作者:行者123 更新时间:2023-12-02 14:16:00 25 4
gpt4 key购买 nike

我正在尝试构建一个函数,该函数允许我从当月开始增加 x 个月。我正在使用 while 循环和 momentjs 我能够增加月份,但在正确增加年份时遇到困难。代码如下:

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));

我得到的结果:

["2016 年 8 月"、"2016 年 9 月"、"2016 年 10 月"、"2016 年 11 月"、"2016 年 12 月"、"2017 年 1 月"、"2017 年 2 月"、"2017 年 3 月”、“2017 年 4 月”、“2017 年 5 月”、“2017 年 6 月”、“2017 年 7 月”、“2017 年 8 月”、“2017 年 9 月”、“2017 年 10 月”、“2017 年 11 月”、“2017 年 12 月”、“2017 年 1 月” ”、“2017 年 2 月”、“2017 年 3 月”、“2017 年 4 月”、“2017 年 5 月”、“2017 年 6 月”、“2017 年 7 月”、“2017 年 8 月”、“2017 年 9 月”、“2017 年 10 月”、“2017 年 11 月” ", "2017 年 12 月"]

年份停留在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>

关于javascript - 使用 While Loop 和 Momentjs 构建一个以年为单位递增月份的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39028402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com