将两个var合并为一个if语句时遇到问题

时间:2018-10-30 17:38:17

标签: javascript if-statement

刚开始编写代码,并且在可视化如何编写此代码方面遇到困难:

var userAge = prompt("Are you old enough to vote? Lets check, enter your age.","");
        var citizen = prompt("Are you a US citizen? Y or N","");

        if(citizen = y && userAge >= 18)  
        {
            alert("Congrats, you can vote!");
        }else
        {
            alert("Sorry you can vote just yet");
        }

        document.write("<br/>");

        if(citizen = n && userAge < 18)
        {
            document.write("but at least you have your youth");

        }else if (citizen = y && userAge > 18)

            {
            document.write("You should be registered to vote! If not, visit www.usa.gov/register-to-vote");
            }

有什么见解?感谢您的时间和支持。

2 个答案:

答案 0 :(得分:1)

您的代码中有一些冗余(因为您有几个地方可以检查两个公民是否都是y并且年龄都在18岁以上(尽管在一个地方您可以检查> =)。但是,我看到的最大问题是是因为您没有用引号引起来的字符串值,而是需要使用==运算符作为比较运算符。单个=运算符是将值分配给变量的赋值运算符。

答案 1 :(得分:0)

  1. 为了进行比较,使用了======用于分配。
  2. 用户输入时,他们的输入将记录为字符串。假设它们只会以大写'Y'或大写'N'进行响应,则您的代码应类似于:

var userAge = prompt("Are you old enough to vote? Lets check, enter your age.", "");
var citizen = prompt("Are you a US citizen? Y or N", "");

if (citizen === 'Y' && userAge >= 18) {
  alert("Congrats, you can vote!");
} else {
  alert("Sorry you can vote just yet");
}

document.write("<br/>");

if (citizen === 'N' && userAge < 18) {
  document.write("but at least you have your youth");
} else if (citizen === 'Y' && userAge > 18) {
  document.write("You should be registered to vote! If not, visit www.usa.gov/register-to-vote");
}