如果,否则,否则-不输出“其他”代码

时间:2019-02-13 19:42:50

标签: javascript if-statement

在运行代码时,前两个选项“生日快乐”起作用,“今年您将____岁”,最后一个选项不起作用。

我尝试了几种不同的代码组合,对于底部代码else来说,什么都不会改变

function getAge() {
  var today = new Date();
  var nowYear = today.getFullYear();
  var nowMonth = today.getMonth();
  var nowDay = today.getDate();

  //prompt user to enter birth year
  var birth = prompt("When were you born?", "YYYY-MM-DD");

  //calculate if birth month is past present furture
  var birth = new
  Date(parseInt(birth.substring(0, 4)), parseInt(birth.substring(5, 7)) - 1, parseInt(birth.substring(8, 10)));

  var birthYear = birth.getFullYear();
  var birthMonth = birth.getMonth();
  var birthDay = birth.getDate();

  //create user string compare birth year and birth month to present date
  var compBirth = birthMonth.toString() + birthDay.toString();
  var compToday = nowMonth.toString() + nowDay.toString();

  //write evaluation
  if (compBirth == compToday) {
    document.write('Today is your Birthday! Happy Birthday!');
  } else if (compBirth < compToday) {
    document.write('You will be turning' + "&nbsp" + (nowYear - birthYear +
      "&nbsp") + 'years old later this year');
  } else {
    document.write('You have turned' + "&nbsp" + (nowYear - birthYear +
      "&nbsp") + 'years old already this year');
  }

}
getAge();

需要所有三个结果才能正确注册输出

2 个答案:

答案 0 :(得分:2)

我修复了您的代码

  • 更改计算compBirthcompToday以将其作为数字进行比较
  • 将条件compBirth < compToday更改为compBirth > compToday(似乎更具逻辑性)

function getAge(){
  var today = new Date();
  var nowYear = today.getFullYear();
  var nowMonth = today.getMonth();
  var nowDay = today.getDate();

  //prompt user to enter birth year
  var birth = prompt("When were you born?", "YYYY-MM-DD");

  //calculate if birth month is past present furture
  var birth = new  Date(parseInt(birth.substring(0,4)),parseInt(birth.substring(5,7))-1,parseInt(birth.substring(8,10)));

  var birthYear = birth.getFullYear();
  var birthMonth = birth.getMonth();
  var birthDay = birth.getDate();

  //create user string compare birth year and birth month to present date
  var compBirth = birthMonth*100 + birthDay;
  var compToday = nowMonth*100 + nowDay;

  //write evaluation
  if( compBirth == compToday) {
    document.write('Today is your Birthday! Happy Birthday!');
  } else if ( compBirth > compToday){
    document.write('You will be turning'+ "&nbsp" + (nowYear - birthYear 
   + "&nbsp") + 'years old later this year');
  }
  else {
    document.write('You have turned' + "&nbsp" + (nowYear - birthYear + 
   "&nbsp") + 'years old already this year');
  }

}
  getAge();

答案 1 :(得分:-2)

如果输入为空,然后单击“确定”,则您的代码可以正常工作。它仅在您单击取消时不起作用,因为取消返回null。为此,您可以再添加一个条件,如下所示:

var birth = prompt("OK?");
else if (result === null) {
    return;
}