简体   繁体   中英

Generate a new random number each time function is called in Javascript

I am trying to learn javascript, I am playing with a game that picks a random number.

I would like to have 2 functions, random and guess. Random generates a new number between 1-10. Guess is where it checks if the number was guessed, if not re-runs the random function and generates a new number to try.

var x;
function random(){
    let x = Math.floor((Math.random() * 10) + 1);
    guess();
 }

function guess(x){
    if(x === 3){
        alert('you are correct!');
    }else{
        alert('try again');
        random();
    }
}

random();

This just alerts try again every time, i'm guessing because it's not generating a new number each time the function is called?

How can you create the random function so it generates a new number each time its called?

***** Correction, it appears to generate a new number but x is undefined within the guess function**

The x in the guess() is the x that gets passed to it as a parameter. I would remove the var x; declaration and pass a value when calling like guess(x)

function random(){
    const x = Math.floor((Math.random() * 10) + 1);
    guess(x);
 }

function guess(x){
    if(x === 3){
        alert('you are correct!');
    }else{
        alert('try again');
        random();
    }
}

random();

The guess function's signature says that it takes a parameter x , but you're not passing any value to the function when it's called, so it's assigning undefined to x when it runs guess , which will never equal 3 . You can take 2 approaches to fix this. First, you could make x a global variable by getting rid of the let where you define x in the random function and removing x from guess 's function signature, like so:

 var x; function random() { x = Math.floor((Math.random() * 10) + 1); guess(); } function guess() { if (x === 3) { alert(x + '- you are correct!'); } else { alert(x + '- try again'); random(); } } random();

Or, you could use x as a parameter for the guess function by removing the var x; global declaration and passing x to guess when you call it in the random function, like so:

 function random() { let x = Math.floor((Math.random() * 10) + 1); guess(x); } function guess(x) { if (x === 3) { alert(x + '- you are correct!'); } else { alert(x + '- try again'); random(); } } random();

I personally wouldn't even have a random function. I'd just define x within guess and call guess from within itself. And, I'd use randojs.com to make the randomness more readable. Here's how I'd do it:

 function guess() { let x = rando(1, 10); if (x === 3) return alert(x + '- you are correct!'); alert(x + '- try again'); guess(); } guess();
 <script src="https://randojs.com/1.0.0.js"></script>

Note that the return statement would stop the execution of the function right then and there, so it wouldn't progress to the "try again" alert if the number was guessed correctly.

I have done some changes to your code. You have problem with the concept of function calling function. In real code it will kill your memory.. your function calls function the function not close and call the function again and again... and its fill the memory .

var x;
// flag correct will close the loop when you have right umber 
var correct = false;
function random() {
    x = Math.floor((Math.random() * 10) + 1);
    guess(x);
}

function guess(x) {
    if (x === 3) {
        alert('you are correct!');
        // if number is right flag is up 
        correct = true;
    } else {
        alert('the number is ' + x + ' try again');
    }
}
// loop until the number is right
while (correct != true) {
    random();
}

Here's some detailed code that will help you understand how to run such a game in the browser.

See the comments for explanation of how it works (and search for information on MDN to learn more about any particular topic.)

Happy coding!

 // Identifies HTML elements const guessInput = document.getElementById("guessInput"), outputParagraph = document.getElementById("outputParagraph"); // Makes a global variable that all functions can access let globalNum; // Invokes the main function playGame(); function playGame(){ // Invokes the randomizer function and stores the result in the global variable globalNum = getRandomNumber(); //console.log(globalNum); // Invokes the output function setOutput("Guess a number from 1 to 10"); // Assigns a function that will be invoked whenever the user changes the input field guessInput.addEventListener("change", respondToGuess); // Puts the focus in the input element guessInput.focus(); } // Defines a listener function that can automatically see the triggering event function respondToGuess(event){ // Gets the `target` element of the event and stores it in a local variable const localReferenceToInputElement = event.target // The text of an `<input>` element lives in its "value" property const inputText = localReferenceToInputElement.value; // Tries to convert the text string to an integer (and store it locally as 'guess') let guess = parseInt(inputText); // If the conversion failed, changes the output accordingly if(!guess){ setOutput("Please enter a valid number"); } // If the number is out of range, changes the output else if(guess < 1 || guess > 10){ setOutput("Only numbers from 1 to 10 are allowed"); } // If the guess doesn't match the stored number, changes the output else if(guess !== globalNum){ setOutput("Try again..."); } // If we got this far, the guess was correct, so changes output and ends game else{ setOutput("You guessed it!"); reset(); } } function getRandomNumber(){ // Returns a random number into whatever function called this function const x = Math.floor((Math.random() * 10) + 1); return x; } function setOutput(outputText){ // The text of a paragraph element lives in its `innerHTML` property outputParagraph.innerHTML = outputText; } function reset(){ // Clears the input and stops listening for changes guessInput.value = ""; guessInput.removeEventListener("change", respondToGuess); }
 <input id="guessInput" /> <p id="outputParagraph"></p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM