gpt4 book ai didi

javascript - 如何获取上一年的月份名称?

转载 作者:行者123 更新时间:2023-12-01 02:00:52 27 4
gpt4 key购买 nike

我被 JavaScript 困住了。我想达到预期的结果。

这是我的代码。

Javascript代码

// Months between years.
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
let joiningDate = new Date("08-08-2017");
let currentDate = new Date();
var months = (currentDate.getFullYear() - joiningDate.getFullYear()) * 12;

// Months between... months.
months += currentDate.getMonth() - joiningDate.getMonth();
var afterDec = currentDate.setDate(12);

if (joiningDate.getDate() < currentDate.getDate()) {
months--;
}

var month = currentDate.getMonth();
for (var i = 0; i < months; i++) {
if (month > 0) {
month = currentDate.getMonth();
console.log(monthNames[month - i]);
}
}

Actual Result on Console

10:48:42.032 points.ts:109 May
10:48:42.033 points.ts:109 Apr
10:48:42.034 points.ts:109 Mar
10:48:42.035 points.ts:109 Feb
10:48:42.037 points.ts:109 Jan
10:48:42.038 points.ts:109 undefined
10:48:42.039 points.ts:109 undefined
10:48:42.039 points.ts:109 undefined

Expected Result on Console

10:48:42.032 points.ts:109 May
10:48:42.033 points.ts:109 Apr
10:48:42.034 points.ts:109 Mar
10:48:42.035 points.ts:109 Feb
10:48:42.037 points.ts:109 Jan
10:48:42.038 points.ts:109 Dec
10:48:42.039 points.ts:109 Nov
10:48:42.039 points.ts:109 Oct

如何添加达到预期效果?

提前致谢。

最佳答案

使用模数回绕到所需的月份。由于 native 模数可以返回负数(不能用于直接查找数组中的索引),因此定义一个 mod 函数,它将返回正(或 0)索引:

const mod = (x, n) => (x % n + n) % n;
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
let joiningDate = new Date("08-08-2017");
let currentDate = new Date();
var months = (currentDate.getFullYear() - joiningDate.getFullYear()) * 12;

// Months between... months.
months += currentDate.getMonth() - joiningDate.getMonth();
var afterDec = currentDate.setDate(12);

if (joiningDate.getDate() < currentDate.getDate()) {
months--;
}

var month = currentDate.getMonth();
for (var i = 0; i < months; i++) {
if (month > 0) {
month = currentDate.getMonth();
console.log(monthNames[mod(month - i, monthNames.length)]);
}
}

关于javascript - 如何获取上一年的月份名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50598502/

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