JavaScript猜数字游戏逻辑错误排查:提示信息不符合预期
Hey George, let's break down what's causing those unexpected messages in your game:
The Core Issues
Condition Order is Backwards
Right now, you're checking if the guess is less than 500 before verifying if it's outside the 1-1500 valid range. So if someone enters a number like 0 (which is both <500 and <1), it triggers the "Try again!" message first instead of the range warning. For numbers over 1500, while they should hit the range check, the lack of type conversion can create unexpected comparison behavior.No Type Conversion for Input Value
Thevalueproperty from your number input returns a string, not a number. When comparing strings to numbers, JavaScript does implicit conversion, but this can lead to edge cases where ordering logic breaks (e.g., string vs numeric value comparisons).
The Fix
Here's the adjusted checkGuess() function to resolve both issues:
var clicks = 0; var click_max = 1500; var click_min = 1; function checkGuess() { // Convert input value to a number to ensure accurate comparisons let txtUserGuess = Number(document.getElementById("userGuess").value); clicks += 1; // Clear the input after each guess for better user experience document.getElementById("userGuess").value = ""; console.log(clicks); if (clicks <= 6) { // First, validate if the guess is within the allowed range if (txtUserGuess < click_min || txtUserGuess > click_max) { swal("Oups..", "Value should be between 1 - 1500", "warning"); } // Check for the correct answer next else if (txtUserGuess === 500) { swal("Good job!", "Correct answer", "success"); } // Catch all valid but incorrect guesses with a single else else { swal("Oups..", "Try again!", "error"); } } else { swal("No more clicks", "Clicks are done", "error"); } }
Key Changes Explained
- Type Conversion: Using
Number()ensures we're comparing actual numbers, eliminating any weird string vs numeric comparison bugs. - Condition Order: We now validate the range first—any number outside 1-1500 immediately shows the range warning, regardless of how it compares to 500.
- Input Cleanup: Fixed the mistake of setting
innerHTMLon an input element (inputs usevalueinstead) and added code to clear the input after each guess. - Simplified Logic: Replaced redundant else-if checks with a final
elseto handle all valid but incorrect guesses, making the code easier to read.
Quick HTML Tweak
Your input has min="0" but your game requires a minimum of 1. Update the input to match your rules:
<input pattern="^[0-9]*$" type="number" min="1" inputmode="numeric" id="userGuess" name="userGuess">
This should fix both of your reported issues: numbers over 1500 will show the range warning, and numbers between 1-499 will correctly display "Try again!".
内容的提问来源于stack exchange,提问作者George Vasilakis

