JavaScript:document.onkeyup捕获变量匹配数组索引及取值异常问题
userChoice Capture in Rock Paper Scissors Game Hey there! Let’s work through why your userChoice isn’t being captured correctly when using document.onkeyup—even though hardcoding values like var userChoice = "r" works fine. Here are the most common fixes and explanations:
1. You’re not grabbing the key from the event object
The biggest culprit here is forgetting to pull the actual pressed key from the keyboard event parameter. When onkeyup fires, it passes an event object that contains details about the key press—you need to use this to get the user’s input.
Here’s a corrected, working example:
// Define your valid game choices const validChoices = ["r", "p", "s"]; // Set up the keyup handler properly document.onkeyup = function(event) { // Capture the pressed key, convert to lowercase to handle uppercase inputs const userChoice = event.key.toLowerCase(); // Check against valid options if (validChoices.includes(userChoice)) { alert(`You chose ${userChoice}! Confirm this selection?`); } else { alert("Please enter a valid choice: 'r' for rock, 'p' for paper, 's' for scissors."); } };
2. Watch out for variable scoping issues
If you declared userChoice outside the event handler but aren’t updating it correctly inside, it might stay undefined or hold an old value. Two ways to fix this:
- Declare
userChoiceinside the handler (like the example above) so it refreshes with every key press - If you need the variable elsewhere, update the external declaration properly:
let userChoice; // Declare outside the handler for broader access const validChoices = ["r", "p", "s"]; document.onkeyup = function(event) { userChoice = event.key.toLowerCase(); // Update the external variable if (validChoices.includes(userChoice)) { alert(`Confirmation: You picked ${userChoice}`); } else { alert("Invalid input—use r/p/s only!"); } };
3. Don’t ignore case sensitivity
Users might press uppercase "R" instead of lowercase "r"—converting the input to lowercase (or adding uppercase options to your valid array) ensures you don’t miss valid selections.
Quick Debug Trick
Add console.log(userChoice) right after assigning it. This will show you exactly what value is being captured in your browser’s dev tools, helping you spot if the issue is with the key input itself or your validation logic.
内容的提问来源于stack exchange,提问作者Ahmed

