简体   繁体   中英

JavaScript - simple program using (conditions, random, boolean)

I have built a small program as a challenge as I am learning JavaScript. The program is build on the function of Math.random, also it uses conditional statements and boolean assignments.

My question is: in the code below i was told that you dont have to strictly equalise the boolean correctGuess to true what is the reason for this, meaning should i do if (correctGuess === true) followed by an else statement or if (correctGuess) then followed by an else statement.

here is the code:

var correctGuess = false;
var randomNumber = Math.floor(Math.random() * 6) + 1;
var guess = prompt("I am thinking of a number between 1 and 6. What is it?");
if (parseInt(guess) === randomNumber ) {
    correctGuess = true;
} else if (parseInt(guess) < randomNumber) {
    var guessMore = prompt(" Sorry, your guess whas too low. Try again");
    if ( parseInt(guessMore) === randomNumber) {
        correctGuess = true;
    }
} else if (parseInt(guess) > randomNumber) {
    var guessLess = prompt("sorry, your guess was too high. Try again");
    if (parseInt(guessLess) === randomNumber) {
        correctGuess = true;
    }
}
if ( correctGuess ) {
    document.write("<p>You guessed the number!<p>");
} else {
    document.write("<p>Sorry. The number was " + randomNumber + ".<p>");
}

if you need to check correctGuess variable to boolean -> if (correctGuess === true) is right choise.

without === in if ( correctGuess ) call you will have true with: correctGuess = {} , correctGuess = [] , correctGuess = "string" , correctGuess = 1 etc.

But if you sure, that correctGuess variable is always boolean (like in your code) - you can use if (correctGuess) call - and it will work perfectly.

You can read more about type conversion here - http://www.w3schools.com/js/js_type_conversion.asp

if i correctly understand question. You don't know difference between if(true === true) and if(true) . this is boolean operand. https://en.wikipedia.org/wiki/Boolean_algebra

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