javascript - 切换大小写仅显示默认值 (JavaScript)

标签 javascript date switch-statement typeerror

我正在尝试制作一个程序,您可以在其中输入您的生日,它会告诉您今天是否是您的生日,您的出生月份,或者您是否需要等待一段时间才能生日。这是:

  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对象,然后调用函数 getMonthgetDate在物体上。

接下来,你的 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') {
}

如果您要根据多种可能性检查值,而必须使用多个 ifelse ifelse,则 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/

相关文章:

javascript - 如何获取选中复选框的值(在jqgrid的页脚中)并发送到 Controller ?

r - 如何得到离每年4月1日最近的星期二?

c - C 中的 switch 语句

java - 使用列表来引用 int 值

java - 切换为 goto 语句还是个案检查器?

javascript - 当使用自定义字体系列时,为什么 safari 的元素宽度与 chrome 和 firefox 报告的有很大不同?

javascript - 根据表单输入更改 html 内容

Javascript 格式返回 0 日

javascript - 如何在 DOJO Toolkit 中实现级联对话框

ruby - 如何找到 Ruby 中两个 Date 对象之间的天数?