我缺少什么,以便我的Logic运算符可以对if-else语句正常工作?

时间:2019-02-13 22:18:38

标签: javascript

我的if-else代码块运行良好,除了最后一个使用AND逻辑运算符的条件。我是JavaScript的新手,我无法弄清楚哪里出了问题!想法?

我尝试添加方括号,删除方括号并重新调整语句。

//declare variables the prompts the user to state their birthdate in 
//month, day and year
var birthYear = prompt('What year were you born in?');
var birthMonth = prompt('What month were you born in? In numerals please!');
var birthDay = prompt('What day of the month were you born on? In numerals please!');

//declare variables to get current date
var now = new Date();
var currentYear = now.getFullYear();
var currentMonth = now.getMonth() + 1; //so now January = 1
var currentDay = now.getDate();
//declare variable for age will turn this year
var age = currentYear - birthYear;
//declare variable for text output
var text = "";
//create if/else loop for three different scenarios
if (birthMonth < currentMonth) {
  text += "You have turned " + age + " years old already this year.";
} else if (birthMonth > currentMonth) {
  text += "You will be turning " + age + " years old later this year.";
} else if (birthMonth === currentMonth && birthDay === currentDay) {
  text += "Today is your Birthday! Happy Birthday!";
}

document.getElementById('agestate').innerHTML = text;
<p id="agestate"></p>

当提示您返回“今天是您的生日。生日快乐!”的提示时,我应该能够输入当前的月份和日期。

2 个答案:

答案 0 :(得分:2)

请勿使用严格等于(===)。标准==应该在这里起作用,因为您的数据类型不兼容:birthMonth是字符串,而currentMonth是整数,因此严格相等将失败。另外,您可以在比较之前将字符串转换为数字(反之亦然)。

您可以尝试以下最新更新的代码(在提示中输入今天的日期以显示“今天是您的生日!”

//declare variables the prompts the user to state their birthdate in 
//month, day and year
var birthYear = prompt('What year were you born in?');
var birthMonth = prompt('What month were you born in? In numerals please!');
var birthDay = prompt('What day of the month were you born on? In numerals please!');

//declare variables to get current date
var now = new Date();
var currentYear = now.getFullYear();
var currentMonth = now.getMonth() + 1; //so now January = 1
var currentDay = now.getDate();
//declare variable for age will turn this year
var age = currentYear - birthYear;
//declare variable for text output
var text = "";

//create if/else loop for three different scenarios
if (birthMonth < currentMonth) {
    text += "You have turned " + age + " years old already this year.";
} else if (birthMonth > currentMonth) {
    text += "You will be turning " + age + " years old later this year.";
} else if (birthMonth == currentMonth && birthDay == currentDay) {
    text += "Today is your Birthday! Happy Birthday!";
}

console.log(text);

答案 1 :(得分:1)

在FrankerZ答案的基础上,request.session函数返回的是字符串而不是数字,但是我不鼓励使用prompt,因为它是javascript严重的随机行为之一,在任何其他情况下(理智)试图比较字符串和数字的语言不会编译或引发错误,但是javascript具有隐藏的行为,具有松散的相等性,您可以详细了解here

我建议您改用数字分析和==(也可以处理缺少的大小写):

===