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

JavaScript:通过getDay()/getMonth()从数组获取日期月份字符串失败

Troubleshooting Date/Month String Retrieval in JavaScript

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 your days array indices
  • getMonth() returns 0 (January) to 11 (December) — which aligns with a full months array

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 days and months arrays have the correct number of elements (7 for days, 12 for months)
  • Always use getDay() for weekday indexing and getMonth() for month indexing when working with 0-based arrays
  • Don't forget to trigger the init function (either with window.onload or an event listener) — otherwise your code won't run when the page loads

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:25:03