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

JavaScript:document.onkeyup捕获变量匹配数组索引及取值异常问题

Troubleshooting 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 userChoice inside 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:28:17