我在学习JavaScript时构建了一个小程序作为挑战。该程序基于Math.random的功能,也使用条件语句和布尔赋值。
我的问题是:在下面的代码中,我被告知你没有必要严格均衡boolean correctGuess到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>");
}
答案 0 :(得分:5)
如果您需要将correctGuess
变量检查为boolean
- &gt; if (correctGuess === true)
是正确的选择。
===
来电中没有if ( correctGuess )
的情况下,您将true
与correctGuess = {}
,correctGuess = []
,correctGuess = "string"
,correctGuess = 1
等
但是,如果您确定,correctGuess
变量始终是boolean
(就像您的代码中一样) - 您可以使用if (correctGuess)
调用 - 它将完美运行。
您可以在此处详细了解类型转换 - http://www.w3schools.com/js/js_type_conversion.asp
答案 1 :(得分:1)
如果我正确理解问题。您不知道if(true === true)
和if(true)
之间的区别。这是布尔操作数。 https://en.wikipedia.org/wiki/Boolean_algebra