我如何动态生成从 2004 年到当前年份的年份数组,每一年都标有“春季”和“秋季”,如附图中所示?
谢谢!
您可以使用flatMap轻松实现此结果。如果您不关心当年的赛季,那么您可以获得截至今年的所有结果。
function generateArrayWithSeason(start) {
return Array(new Date().getFullYear() + 1 - start)
.fill("")
.flatMap((_, i) => [`${start + i} SPRING`, `${start + i} FALL`]);
}
console.log(generateArrayWithSeason(2004));
.as-console-wrapper { max-height: 100% !important; top: 0; }
如果您想要根据当年的结果spring
和fall
春季从 3 月 1 日持续到 5 月 31 日
秋季(秋季)从 9 月 1 日到 11 月 30 日
function generateArrayWithSeason(start) {
const month = new Date().getMonth();
let currentYear = new Date().getFullYear();
const springMonths = [3, 4, 5];
const fallMonths = [9, 10, 11];
return Array(currentYear + 1 - start)
.fill("")
.flatMap((_, i) => {
if (currentYear === start + i) {
if (springMonths.includes(month)) return [`${start + i} SPRING`];
if (fallMonths.includes(month)) return [`${start + i} FALL`];
}
return [`${start + i} SPRING`, `${start + i} FALL`];
});
}
console.log(generateArrayWithSeason(2004));
.as-console-wrapper { max-height: 100% !important; top: 0; }
以下代码将返回一个字符串数组,其中包含"<year> <SPRING/FALL>"
从 2004 年到当前日期的字符串,不包括当年的春季或秋季(如果它们尚未发生)。
const seasons = {
2: 'SPRING',
8: 'FALL',
};
const now = new Date();
const output = [];
for (let current = new Date(2004, 2, 1); current <= now; current.setMonth(current.getMonth() + 6)) {
output.push(`${current.getFullYear()} ${seasons[current.getMonth()]}`);
}
console.log(output);