繁体   English   中英

JavaScript-使用(条件,随机,布尔)的简单程序

[英]JavaScript - simple program using (conditions, random, boolean)

在学习JavaScript时,我已经构建了一个小程序来应对挑战。 该程序建立在Math.random函数的基础上,还使用条件语句和布尔赋值。

我的问题是:在下面的代码中,我被告知您不必严格地将booleancorrectGuess均等化为true,这是什么原因,这意味着我应该在if (correctGuess === true)后接else语句还是if (correctGuess)再接着一个else语句。

这是代码:

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>");
}

如果您需要将correctGuess变量检查为boolean -> if (correctGuess === true)是否正确。

没有===if ( correctGuess )调用,您将具有truecorrectGuess = {}correctGuess = []correctGuess = "string"correctGuess = 1等。

但是,如果您确定,则correctGuess变量始终为boolean (如您的代码中一样)-您可以使用if (correctGuess)调用-它将完美地工作。

您可以在此处详细了解类型转换-http: //www.w3schools.com/js/js_type_conversion.asp

如果我正确理解问题。 您不知道if(true === true)if(true)之间的区别。 这是布尔操作数。 https://en.wikipedia.org/wiki/Boolean_algebra

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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