简体   繁体   中英

Javascript If else returns either only TRUE or only FALSE

<body>
<input id ="guessNumber" type="text">
<button id="button" onclick="check()">click here</button>



<script language="javascript" type="text/javascript">
var randomNumber = Math.floor((Math.random()*6));
var guessNumber = document.getElementById("guessNumber").value;

function check() {
    if(guessNumber==randomNumber){
        alert("you are correct");
    }
    else {
        alert("you are wrong");
    }
}
</script>
</body>

I want to write a small number game program where I put in a number and if the Math.random method value are equal it should alert "TRUE" but its just alerting "FALSE"("it is wrong" my alert code) all the time.Give me an explanation why that is happening not just the answer and why is guessNumber variable a string ?

This line is outside of the function.

var guessNumber = document.getElementById("guessNumber").value;

It gets the value once, it does not update as the text changes. Move it inside the method.

Second issue, you are comparing a number and a string. The value of an input is a string. You are trying to compare a number and a string. Type console.log("3"===3); into your console.

 var randomNumber = Math.floor((Math.random() * 6)); function check() { var guessNumber = parseInt(document.getElementById("guessNumber").value, 10); if (guessNumber === randomNumber) { alert("you are correct"); } else { alert("you are wrong"); } } 
 <input id="guessNumber" type="text"> <button id="button" onclick="check()">click here</button> 

Maybe if you run a test like this you will understand

 var randomNumber = Math.floor((Math.random() * 6)); var initialValue = document.getElementById("guessNumber").value; var currentValue; function check() { currentValue = document.getElementById("guessNumber").value; alert("initialValue: " + initialValue + " | currentValue: " + currentValue + " | randomNumber : " + randomNumber); var guessNumber = parseInt(currentValue, 10); if (guessNumber === randomNumber) { alert("you are correct"); } else { alert("you are wrong"); } } 
 <input id="guessNumber" type="text" value="INITIAL VALUE"> <button id="button" onclick="check()">click here</button> 

guessNumber is a string and randomNumber is a number. Try this:

function check() {
    if(guessNumber==randomNumber){
        alert("you are correct");
    }
    else {
        alert("you are wrong");
    }
}

https://stackoverflow.com/a/359509/2690289

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