在运行代码时,前两个选项“生日快乐”起作用,“今年您将____岁”,最后一个选项不起作用。
我尝试了几种不同的代码组合,对于底部代码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' + " " + (nowYear - birthYear +
" ") + 'years old later this year');
} else {
document.write('You have turned' + " " + (nowYear - birthYear +
" ") + 'years old already this year');
}
}
getAge();
需要所有三个结果才能正确注册输出
答案 0 :(得分:2)
我修复了您的代码
compBirth
和compToday
以将其作为数字进行比较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'+ " " + (nowYear - birthYear
+ " ") + 'years old later this year');
}
else {
document.write('You have turned' + " " + (nowYear - birthYear +
" ") + 'years old already this year');
}
}
getAge();
答案 1 :(得分:-2)
如果输入为空,然后单击“确定”,则您的代码可以正常工作。它仅在您单击取消时不起作用,因为取消返回null。为此,您可以再添加一个条件,如下所示:
var birth = prompt("OK?");
else if (result === null) {
return;
}