gpt4 book ai didi

JavaScript - 使用(条件、随机、 bool 值)的简单程序

转载 作者:太空宇宙 更新时间:2023-11-03 20:10:52 24 4
gpt4 key购买 nike

在学习 JavaScript 的过程中,我构建了一个小程序作为挑战。该程序建立在 Math.random 函数的基础上,它还使用条件语句和 bool 赋值。

我的问题是:在下面的代码中我被告知您不必将 bool 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 with: correctGuess = {}correctGuess = []correctGuess = "string"correctGuess = 1

但是,如果您确定 correctGuess 变量始终是 boolean(就像在您的代码中一样)- 您可以使用 if (correctGuess) 调用- 它将完美运行。

您可以在此处阅读有关类型转换的更多信息 - http://www.w3schools.com/js/js_type_conversion.asp

关于JavaScript - 使用(条件、随机、 bool 值)的简单程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33648831/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com