JS根据星期几显示消息报错:day is not defined 求助
Hey there! Sorry you're stuck with that "day is not defined" error—let's break this down and get your weekday message working properly.
First off, that error means you're trying to use a variable called day somewhere in your code, but you never actually created that variable or gave it a value. The missing piece here is getting the current day of the week from JavaScript's Date object.
Let's start by fixing that core issue, then build out the rest of the functionality. Here's a complete, working example that ties in your existing checkTime function (we'll keep it since you included it in your snippet):
// Your existing time formatting function function checkTime(i) { if (i < 10) { i = "0" + i; } return i; } function showWeekdayMessage() { // Step 1: Get the current day of the week const today = new Date(); const day = today.getDay(); // Returns 0 (Sunday) to 6 (Saturday) let message; // Step 2: Set a message based on the day // Using switch for clean readability, but if/else works too! switch(day) { case 0: message = "今天是周日,好好放松休息吧!"; break; case 1: message = "周一到啦,打起精神开启新一周!"; break; case 2: message = "周二,继续稳步前进哦!"; break; case 3: message = "周三,一周已经过半啦!"; break; case 4: message = "周四,再坚持一天就到周末啦!"; break; case 5: message = "周五!终于可以准备享受假期啦🥳"; break; case 6: message = "周六,尽情享受休闲时光吧!"; break; default: message = "哎呀,好像出了点小问题,没法识别今天是星期几😅"; } // Step 3: Display the message on the page // Make sure you have an element with this ID in your HTML! document.getElementById("weekdayMessage").innerHTML = message; } // Call the function to run it showWeekdayMessage();
Key fixes & notes:
- Declaring the
dayvariable: This is the main fix for your "day is not defined" error. We usenew Date()to get the current date/time, thengetDay()to pull the numeric day value (0-6). Without this line, JavaScript has no idea whatdayrefers to! - Using if/else instead (if you prefer): If switch statements feel unfamiliar, you can replace that section with
if/else ifblocks:let message; if (day === 0) { message = "周日快乐!"; } else if (day === 1) { message = "周一加油!"; } // Add the rest of the day checks here - HTML element requirement: Make sure your page has an element where the message can display, like:
<div id="weekdayMessage"></div> - Running the function: If you want the message to show up as soon as the page loads, you can wrap the function call in
window.onloadto ensure the page is fully loaded first:window.onload = function() { showWeekdayMessage(); };
Give this a try, and let me know if you hit any other bumps along the way!
内容的提问来源于stack exchange,提问作者Kirk

