JavaScript猜数字游戏重置问题:旧随机数未更新求助
Hey there! I see exactly what's going on here—your reset button is clearing the input and UI, but it's not generating a new random number for the next game. That's why the old number sticks around even after you reset.
The Problem
You initialize actualNum once at the top of your code with var actualNum = randomNumber();, but you never update this variable when the reset button is clicked. So every new game after a reset is still using the original random number instead of a fresh one.
The Fix
All you need to do is update the reset() function to:
- Generate a new random number and assign it to
actualNum - Clear the UI display (your current
removeChildapproach can be simplified withinnerHTML = ""to avoid potential errors)
Here's the updated reset function:
function reset(){ // Generate a new random number for the next game actualNum = randomNumber(); // Clear the input field document.getElementById('input').value = ""; // Clear the guess result UI document.getElementById('player-guess').innerHTML = ""; }
Full Updated Code
For reference, here's your complete code with the fix applied:
var actualNum = randomNumber(); function randomNumber(){ return Math.floor(Math.random() * 101); } function findCorrectGuess(actualNum,userGuess){ if(userGuess > actualNum){ return "That is too high!" } else if (userGuess < actualNum){ return "That is too low!" } else if (userGuess === actualNum){ return "BOOM!" } } function reset(){ actualNum = randomNumber(); // This line is the key fix! document.getElementById('input').value = ""; document.getElementById('player-guess').innerHTML = ""; } function clearField(){ document.getElementById('input').value = ""; } function guessToUI(){ let userGuess = document.getElementById('input').value; document.getElementById('player-guess').innerHTML = `<center><h1>Your last guess was</h1><h2>${userGuess}</h2><h3>${findCorrectGuess(parseInt(actualNum),parseInt(userGuess))}</h3></center>` } function listeners(){ document.getElementById('guesser').addEventListener('click', guessToUI); document.getElementById('clear').addEventListener('click', clearField); document.getElementById('reset').addEventListener('click', reset); } listeners();
Why This Works
When you click reset now, it does three things:
- Creates a brand new random number and stores it in
actualNum, so the next round of guessing uses this new value - Clears the input field so the player can start fresh
- Wipes the previous guess result from the UI, giving a clean slate for the new game
Go ahead and test this out—after guessing correctly, click reset, and your next guesses will be against a brand new random number!
内容的提问来源于stack exchange,提问作者user3763875

