我正在尝试制作一个您输入生日的程序,它会告诉您今天是您的生日,您的出生月份,还是您需要等待一段时间直到您的生日。这是:
function isB_Day (month, day) {
var m = Date.getMonth();
var d = Date.getDate();
switch (month) {
case month === m:
if(day === d){
alert('Happy Birthday To You!');
} else {
alert('Almost your B-Day dude!');
};
break;
default: alert('You B-day won\'t be for a little while, bud. Hang in there!');
};
};
但是当我把:
isB_Day(0, 27);
(因为它是1月27日) 它给我一个错误说:
VM332:2 Uncaught TypeError: Date.getMonth is not a function
at isB_Day (<anonymous>:2:16)
at <anonymous>:20:1
请帮忙!
答案 0 :(得分:1)
您只需要初始化Date
对象,然后调用对象上的函数getMonth
和getDate
。
接下来,你的switch语句有点错误。您正在使用case (month === m):
类似if
语句。但是,switch语句基本上就是说如果事情与switch参数匹配。
// this will check the string 'justin' against any case statement.
switch('justin') {
case 'test':
break;
}
// the same if statement would be
if ('justin' == 'test') {
}
如果您要针对多种可能性检查值,而且必须包含多个if
,else if
,else
语句,则切换语句非常有用。
function isB_Day(month, day) {
// initialize a Date object
var now = new Date();
// call getMonth on the object
var m = now.getMonth();
// call getDate on the object
var d = now.getDate();
// you are passing month into the switch
switch (month) {
// this checks the switch month against the case m
case m:
if (day === d) {
console.log('Happy Birthday To You!');
} else if (d > day) {
console.log('Your birthday already happened this month');
} else {
console.log('Almost your B-Day dude!');
}
break;
default:
console.log("You B-day won't be for a little while, bud. Hang in there!");
break;
}
}
isB_Day(0, 27);
isB_Day(0, 28);
isB_Day(1, 28);
// shows that Date is a native function
console.log(Date);
console.log(Date());
// Date is a function without calling the function it doesn't have the getMonth function
console.log(Date.getMonth());