在学习JavaScript时,我已经构建了一个小程序来应对挑战。该程序建立在Math.random函数的基础上,还使用条件语句和布尔赋值。
我的问题是:在下面的代码中,我被告知您不必严格地将布尔的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>");
}
最佳答案
如果需要将correctGuess
变量检查为boolean
-> 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