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
keyproperty (using template literals for cleaner string creation) instead of plain strings into the array, which gives you the exactoptionsstructure you requested.
内容的提问来源于stack exchange,提问作者developer

