You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现未来6个月年月键值对数组的技术问题

Hey there! Let's get your array formatted exactly how you need it. You're already halfway there with generating the month-year strings—we just need to adjust how we build the final array to match that {key: "Month Year"} structure.

Solution

Basic Fix (For Non-Cross-Year Scenarios)

If you don't expect the 6-month window to cross into the next year (e.g., current month is January-July), you can simply modify the line where you push items into the array to create objects instead of plain strings:

const d = new Date();
const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
const year = d.getFullYear();
let options = []; // Renamed to match your target variable name

for(let i = 1 ; i < 7 ; i++){
  let currentMonthIndex = d.getMonth();
  let targetMonthIndex = currentMonthIndex + i;
  let monthYear = `${monthNames[targetMonthIndex]} ${year}`;
  // Push an object with the "key" property instead of the string directly
  options.push({ key: monthYear });
}

console.log(options);

Robust Version (Handles Year Transitions)

If your 6-month window might span into the next year (e.g., current month is August-December), the above code will break because monthNames only has indexes 0-11. Here's a version that accounts for year changes automatically:

const d = new Date();
const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
let options = [];

for(let i = 1 ; i < 7 ; i++){
  // Create a date object for the target month (current + i months)
  const targetDate = new Date(d.getFullYear(), d.getMonth() + i, 1);
  const month = monthNames[targetDate.getMonth()];
  const year = targetDate.getFullYear();
  options.push({ key: `${month} ${year}` });
}

console.log(options);

What Changed?

  • Instead of calculating month indexes manually, we use new Date() to handle month/year rollover automatically—this is far more reliable for edge cases.
  • We now push objects with a key property (using template literals for cleaner string creation) instead of plain strings into the array, which gives you the exact options structure you requested.

内容的提问来源于stack exchange,提问作者developer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:35:51