JavaScript:通过getDay()/getMonth()从数组获取日期月份字符串失败
Hey there! Let's work through why you're having trouble pulling those weekday and month strings from your arrays. This is a super common hiccup when getting started with JavaScript's Date object, so let's break down the likely issues and fix them up:
Common Issues & Fixes
1. Incomplete Month Array
Looking at your code snippet, the months array cuts off at "No..." — that means you're missing the final two entries ("Nov" and "Dec"). If you try to access months at index 10 or 11 (which correspond to November and December via the Date object), you'll get undefined because those positions don't exist in your array.
2. Mismatched Date Methods
JavaScript's Date object uses 0-based indexing for both weekdays and months:
getDay()returns 0 (Sunday) to 6 (Saturday) — perfect for matching yourdaysarray indicesgetMonth()returns 0 (January) to 11 (December) — which aligns with a fullmonthsarray
If you accidentally used getDate() (which returns the day of the month, 1-31) instead of getDay(), or tried to use a 1-based index for months, that would break the array lookup.
Corrected Code Example
Here's a full, working version of your code with fixes and explanations:
function init(){ var panel = document.getElementById("panel"); var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; // Complete the months array with all 12 entries var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; // Create a Date object to get the current date/time var currentDate = new Date(); // Use getDay() to get the 0-6 index for the days array var weekday = days[currentDate.getDay()]; // Use getMonth() to get the 0-11 index for the months array var monthName = months[currentDate.getMonth()]; // Output the result to the panel element panel.innerHTML = `Current date: ${weekday}, ${monthName} ${currentDate.getDate()}`; } // Make sure to run the init function when the page loads window.addEventListener('load', init);
Key Notes
- Double-check that your
daysandmonthsarrays have the correct number of elements (7 for days, 12 for months) - Always use
getDay()for weekday indexing andgetMonth()for month indexing when working with 0-based arrays - Don't forget to trigger the
initfunction (either withwindow.onloador an event listener) — otherwise your code won't run when the page loads
内容的提问来源于stack exchange,提问作者user9132313

