课程作业需求:将现有可用成绩录入代码封装为函数并优化终止方式
Solution: Wrap Grade Entry Logic into a Function & Improve Termination Flow
Hey there! Let's spruce up your grade entry code—first wrapping it into a reusable function, then ditching that awkward 999 termination for something more user-friendly.
1. Encapsulating into a Reusable Function
We’ll move all the grade-handling logic into a myFunction() so it’s modular, doesn’t clutter the global scope, and can be called whenever you need it. All variables will live inside the function to keep things clean.
2. Better Termination Alternatives
Using 999 as a stop signal is clunky (what if someone accidentally enters it? Or worse, a hypothetical course uses 999 as a valid score?). Here are two intuitive fixes we’ll implement:
- Allow clicking "Cancel": When users hit Cancel in the prompt, it returns
null—we can use this to exit the loop naturally. - Accept text commands: Let users type "quit" or "q" to stop entering grades, which is explicit and easy to understand.
Modified Full Code
Here’s the updated version with both improvements, plus some UX tweaks:
<!DOCTYPE html> <html> <body> <script> function myFunction() { let entry; let letterGrade; let total = 0; let entryCount = 0; const errorString = "Entry must be a valid number from 0 through 100.\nClick Cancel or type 'quit' to end entries"; do { entry = prompt("Enter number grade from 0 through 100.\nClick Cancel or type 'quit' to end entries", ""); // Exit if user clicks Cancel if (entry === null) { break; } // Exit if user types quit command (case-insensitive) const cleanedEntry = entry.toLowerCase().trim(); if (cleanedEntry === "quit" || cleanedEntry === "q") { break; } // Validate numeric input if (isNaN(entry)) { alert(errorString); } else { entry = parseInt(entry); if (entry >= 0 && entry <= 100) { // Map number grade to letter grade if (entry < 50) { letterGrade = "F"; } else if (entry < 70) { letterGrade = "D"; } else if (entry < 80) { letterGrade = "C"; } else if (entry < 90) { letterGrade = "B"; } else { letterGrade = "A"; } total += entry; entryCount += 1; alert(`Number grade = ${entry}\nLetter grade = ${letterGrade}`); } else { alert(errorString); } } } while (true); // Loop until we hit a termination condition // Show a summary after exiting if (entryCount > 0) { const average = (total / entryCount).toFixed(2); alert(`Entry complete!\nTotal grades entered: ${entryCount}\nTotal points: ${total}\nAverage grade: ${average}`); } else { alert("No grades were entered."); } } // Run the function when the page loads myFunction(); </script> </body> </html>
Key Changes Breakdown:
- Function Encapsulation: All variables are now local to
myFunction(), so no global scope pollution. You can call this function multiple times without conflicts. - Intuitive Termination: Users have two clear ways to stop entering grades—clicking Cancel or typing a simple command.
- Improved UX: Updated prompt/error messages to explicitly explain how to exit, plus a helpful summary alert with total points, entry count, and average grade.
- Modern Syntax: Swapped
varforlet/constfor better block scoping, and used template literals (${}) to make string concatenation cleaner.
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

