gpt4 book ai didi

javascript - 如何重启阵列?

转载 作者:行者123 更新时间:2023-11-28 11:43:56 25 4
gpt4 key购买 nike

我有代码可以提醒当前月份加上过去两个月:

 var cMonth = new Date().getMonth();
var currentMonth, pastMonth2, pastMonth3 = 0

var months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]
currentMonth = months[cMonth];
pastMonth2 = months[cMonth - 1];
pastMonth3 = months[cMonth - 2];

alert(pastMonth3 + " " + pastMonth2 + " " + currentMonth);

但是,如果月份是一月或二月,我希望它“重新启动数组”并打印十二月和十一月,基本上打印数组的最后一个元素。我能想到的唯一解决方法是使用 if 语句添加验证,但它们无法正常工作,更不用说我觉得这不是一个足够的解决方案(如果不是几个月是一个月中的几天,并且我想打印最后一个,该怎么办? 12天?)

  if(cMonth == 1){ //prints Undefined Jan, Feb
currentMonth = months[1]
pastMonth2 = months[0]
pastMonth3 = months[11]
}
if (cMonth == 0) { //prints Nov, Dec and Jan!
currentMonth = months[0]
pastMonth2 = months[11]
pastMonth3 = months[10]
} else {
currentMonth = months[cMonth];
pastMonth2 = months[cMonth - 1];
pastMonth3 = months[cMonth - 2];
}

alert(pastMonth3 + " " + pastMonth2 + " " + currentMonth);

最佳答案

Date.toLocaleString可用于获取月份名称:

const monthName = m => new Date(0, m).toLocaleString('en-US', { month: 'long' })

var month = new Date().getMonth();

console.log( monthName(month ) ) // currentMonth
console.log( monthName(month - 1) ) // pastMonth2
console.log( monthName(month - 2) ) // pastMonth3

console.log( monthName(-2) ) // November
console.log( monthName(13) ) // February

关于javascript - 如何重启阵列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57128048/

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