【问题标题】:the switch-statement gives the wrong month how to fix?switch 语句给出了错误的月份如何解决?
【发布时间】:2013-11-07 20:17:27
【问题描述】:

我正在尝试获取当前月份,然后将月份放在 div 中。

function checkmaand()
{
var datum = new Date();
var maand = datum.getMonth();
switch (maand)
{   
    case 0: document.getElementById("maand").innerHTML = "Januari";
    case 1: document.getElementById("maand").innerHTML = "Februari";
    case 2: document.getElementById("maand").innerHTML = "Maart";
    case 3: document.getElementById("maand").innerHTML = "April";
    case 4: document.getElementById("maand").innerHTML = "Mei";
    case 5: document.getElementById("maand").innerHTML = "Juni";
    case 6: document.getElementById("maand").innerHTML = "Juli";
    case 7: document.getElementById("maand").innerHTML = "Augustus";
    case 8: document.getElementById("maand").innerHTML = "September";
    case 9: document.getElementById("maand").innerHTML = "Oktober";
    case 10: document.getElementById("maand").innerHTML = "November";
    case 11: document.getElementById("maand").innerHTML = "December";
}
}

但由于某种原因,输出是 12 月(对于未来的人来说现在是 11 月)

所以我的问题是它为什么会这样做,我该如何解决?

还有一件事:我必须用 javascript 来实现。

【问题讨论】:

  • 提示:将 document.getElementById("maand") 设置为变量而不是重复它。 var target = document.getElementById("maand"),然后使用 target.innerHTML(...);
  • @Diodeus 或者更简单:将 monts 存储在一个变量中,并将其附加在 swich 语句之后。 @OP:您缺少 break; 语句(和默认值),因此您总是会得到最后一个值。

标签: javascript switch-statement monthcalendar


【解决方案1】:

您必须在每个案例的末尾添加一个break;,以便它不会继续到下一个。

function checkmaand()
{
var datum = new Date();
var maand = datum.getMonth();
switch (maand)
{   
    case 0: document.getElementById("maand").innerHTML = "Januari";
        break;
    case 1: document.getElementById("maand").innerHTML = "Februari";
        break;
   ...
}
}

等等

【讨论】:

    【解决方案2】:

    你错过了每个案例结尾的“休息”。

    【讨论】:

      【解决方案3】:

      正如其他人所提到的,问题是因为您忘记在每个案例陈述的末尾添加break;

      作为建议,您可以简化代码,例如 this:

      function checkmaand() {
          document.getElementById("maand").innerHTML = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][new Date().getMonth()];
      }
      

      【讨论】:

        【解决方案4】:
        switch (expr) {
          case "Oranges":
            document.write("Oranges are $0.59 a pound.<br>");
            break;
          case "Apples":
            document.write("Apples are $0.32 a pound.<br>");
            break;
        

        HC_为例。

        休息是可选的,但解释会显示:

        与每个 case 标签关联的可选 break 语句确保程序在执行匹配的语句后跳出 switch,并在 switch 后面的语句处继续执行。 如果省略break,程序会在switch语句中的下一条语句继续执行

        【讨论】:

          猜你喜欢
          • 2012-09-13
          • 1970-01-01
          • 1970-01-01
          • 2022-11-19
          • 2019-04-04
          • 1970-01-01
          • 2022-07-20
          • 2011-12-08
          • 1970-01-01
          相关资源
          最近更新 更多