JavaScript语法错误或更多?

时间:2015-04-29 01:02:04

标签: javascript syntax-error feedback

我是一个非常新的(读作三小时)业余爱好者,所以我有一个非常低级别的问题。但是我认为这将提供一个很好的机会来探索这个stackoverflow社区。我已经完成了约50%的CodeAcademy JavaScript简介,刚刚完成了while和for循环的部分。在自由练习部分,我决定尝试编写一个程序来模拟1000次硬币翻转并将结果报告给用户。该程序似乎运行正常,但在第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);

4 个答案:

答案 0 :(得分:3)

这一行:

if (userReady = "yes" || "Yes") {

不符合您的预期。首先,您不能使用=来比较值(这意味着在Javascript中进行分配)。所以你可以使用===。其次,||加入两个独立的条件,而不是值。所以你可以写:

if (userReady === "yes" || userReady === "Yes") {

此外,您可以通过在比较之前规范用户输入的大小写来覆盖用户输入YESyEs之类的情况:

if (userReady.toLowerCase() === "yes") {

答案 1 :(得分:1)

你的if语句只查找布尔语句(其中&#34;是&#34;不是一个)。此外,=是赋值运算符,而==是比较运算符。将if语句行更改为以下内容将解决问题。

if (userReady == "yes" || userReady == "Yes") {

答案 2 :(得分:1)

我对代码做了一些更改: 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!");
}

答案 3 :(得分:0)

当您比较值时,您应该使用==而不是=,对于操作也不正确,您需要执行以下操作: if(userReady ==&#34; yes&#34; || userReady ==&#34; Yes&#34;)