简体   繁体   中英

JavaScript return from function only working once

I want to give the addition of two random numbers and let the user input correct answer but its stuck to the same answer

 function start(){ var fst = document.getElementById("fst").innerHTML = Math.floor(Math.random()*10); var snd = document.getElementById("snd").innerHTML = Math.floor(Math.random()*10); return fst+snd; } var x = start() function validate(){ var txt = document.getElementById("txt").value; if(txt==x){ console.log('Correct Answer'); } else console.log('Wrong Answer'); start(); } 

In your validate() function, you compare the user's input with x , then generate new random numbers by calling start() . However, the value of x is never updated, so the x is always equal to the first two random numbers that are generated.

Instead of calling start() at the end of the validate() function, assign x to the value of start() like this: x = start() .

This way, new random numbers will be generated, and the value of x will be assigned the sum of the new numbers.

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