[英]JavaScript Syntax Error or More?
我是JavaScript的新手(大约三个小时大),所以我有一个非常低级的问题。 但是我认为这将为探索这个stackoverflow社区提供了一个很好的机会。 我已经遍历了大约50%的CodeAcademy JavaScript简介,并且刚刚完成了while和for循环部分。 在免费练习部分,我决定尝试编写一个程序来模拟掷硬币1,000次并将结果报告给用户。 该程序似乎运行正常,但是在第9行上,我引入了if / else语句,提示语法错误。 现在我还看到,如果您回答“否”,它仍然可以运行。 语法有什么问题,您对我的第一个独立程序有何其他一般反馈? 谢谢!
var userReady = prompt("Are you ready for me to flip a coin one thousand times?");
var flipCount = 0;
var heads = 0;
var tails = 0;
if (userReady = "yes" || "Yes") {
flipCount++;
while (flipCount <= 1000) {
var coinFace = Math.floor(Math.random() * 2);
if (coinFace === 0) {
heads++;
flipCount++;
} else {
tails++;
flipCount++;
}
}
} else {
confirm("Ok we'll try again in a second.");
var userReady = prompt("Are you ready now?");
}
confirm("num of heads" + " " + heads);
confirm("num of tails" + " " + tails);
var userReady = prompt("Are you ready for me to flip a coin one thousand times?"); var flipCount = 0; var heads = 0; var tails = 0; if (userReady = "yes" || "Yes") { flipCount++; while (flipCount <= 1000) { var coinFace = Math.floor(Math.random() * 2); if (coinFace === 0) { heads++; flipCount++; } else { tails++; flipCount++; } } } else { confirm("Ok we'll try again in a second."); var userReady = prompt("Are you ready now?"); } confirm("num of heads" + " " + heads); confirm("num of tails" + " " + tails);
这行:
if (userReady = "yes" || "Yes") {
不按照您的期望去做。 首先,您不能使用=
来比较值(这意味着用Javascript赋值)。 因此,您可以使用===
。 第二, ||
连接两个独立的条件,而不是值。 所以你可以这样写:
if (userReady === "yes" || userReady === "Yes") {
此外,您可以覆盖情况:用户类型类似YES
或者yEs
通过比较之前标准化用户输入的情况下:
if (userReady.toLowerCase() === "yes") {
您的if语句仅查找布尔语句(其中“ Yes”不是一个)。 同样, =
是赋值运算符,而==
是比较运算符。 将if语句行更改为以下内容将解决问题。
if (userReady == "yes" || userReady == "Yes") {
我对代码进行了一些更改:1.添加了默认答案“是” 2.将while循环更改为for循环(在您的代码中,您可以将flipCount直接放在else语句之后)3.更改了确认以提醒4 。使一次警报中的头和尾数
var userReady = prompt("Would you like to run a coin simulator?" + "\n"
+ "Answer yes or no:","Yes");
if(userReady.toLowerCase() === "yes")
{
var heads = 0, tails = 0;
for (var flipCount = 0; flipCount < 1000; flipCount++)
{
var coinFace = Math.floor(Math.random() * 2);
if (coinFace === 0)
{
heads++;
}
else
{
tails++;
}
}
alert("Number of heads: " + heads + "\n"
+ "Number of tails: " + tails);
}
else
{
// statement goes here if the user doesn't want to play
//alert("You're no fun!");
}
比较值时,应使用==而不是=, 或者由于其操作不正确,您需要执行以下操作:if(userReady ==“ yes” || userReady ==“ Yes”)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.