我正在尝试制作一个程序,您可以在其中输入您的生日,它会告诉您今天是否是您的生日,您的出生月份,或者您是否需要等待一段时间才能生日。这是:
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
请帮忙!
最佳答案
描述
您只需初始化 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
,则 Switch 语句非常有用> 声明。
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());
关于javascript - 切换大小写仅显示默认值 (JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41907209/