Javascript - 使用 "IF" 与 "SWITCH" 将 toDateString 月份从文本字符串解析为数字字符串

Javascript - Parsing toDateString Month from a text string to number string using "IF" vs "SWITCH"

关于在 Javascript 中使用 IF 语句与 SWITCH,我有一个可能非常简单的问题。我正在尝试以 "Month/Day/Year" 格式将当前日期添加到我的页面,其中 "Month" 是一个数字,如“03/30/2015”。我已经能够使用下面的代码解决这个问题:http://jsfiddle.net/mshirk/zre1y20r/

var d = new Date();
var dd = d.toDateString();
var ddd = dd.split(' '); 
ddd.shift();    
var mon = ddd[0];
var da = ddd[1];
var yr =ddd[2];
if (mon == "Jan"){monb = 1;}
if (mon == "Feb"){monb = 2;}
if (mon == "Mar"){monb = 3;}
if (mon == "Apr"){monb = 4;}
if (mon == "May"){monb = 5;}
if (mon == "Jun"){monb = 6;}
if (mon == "Jul"){monb = 7;}
if (mon == "Aug"){monb = 8;}
if (mon == "Sep"){monb = 9;}
if (mon == "Oct"){monb = 10;}
if (mon == "Nov"){monb = 11;}
if (mon == "Dec"){monb = 12;}
slashDate = monb + "/" + da + "/" + yr;
document.getElementById('titleDate').innerHTML = slashDate;

不过,我的理解是这里使用SWITCH语句会更好。所以我用 SWITCH 语句替换了冗长的 IF 语句,如下所示:http://jsfiddle.net/mshirk/q0mfds0t/2/

var d = new Date();
var dd = d.toDateString();
var ddd = dd.split(' '); 
ddd.shift();    
var mon = ddd[0];
var da = ddd[1];
var yr =ddd[2];
switch(mon){
    case "Jan": monb = 01;
    case "Feb": monb = 02;
    case "Mar": monb = 03;
    case "Apr": monb = 04;
    case "May": monb = 05;
    case "Jun": monb = 06;
    case "Jul": monb = 07;
    case "Aug": monb = 08;
    case "Sep": monb = 09;
    case "Oct": monb = 10;
    case "Nov": monb = 11;
    case "Dec": monb = 12;
}
slashDate = monb + "/" + da + "/" + yr;
document.getElementById('titleDate').innerHTML = slashDate;

问题是SWITCH语句产生的日期是错误的!?!?任何人都可以帮助解释为什么 IF 语句产生的日期是正确的而 SWITCH 语句产生的日期不正确?任何帮助将非常感激! 谢谢

每个病例后你需要休息

switch(mon){
case "Jan": monb = 01; break;
case "Feb": monb = 02; break;
case "Mar": monb = 03; break;
case "Apr": monb = 04; break;
case "May": monb = 05; break;
case "Jun": monb = 06; break;
case "Jul": monb = 07; break;
case "Aug": monb = 08; break;
case "Sep": monb = 09; break;
case "Oct": monb = 10; break;
case "Nov": monb = 11; break;
case "Dec": monb = 12; break;
} 

如果未提供 break 语句,则 switch 将继续命中下一个 case,即使该 case 不符合给定 switch 的条件。 在这种情况下,如果没有 break 语句,它总是 return 12 for monb.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch#What_happens_if_I_forgot_a_break

你需要 break 关键字来跳过其他条件

  switch(mon){
    case "Jan": monb = 01;break ;
    case "Feb": monb = 02;break ;
    case "Mar": monb = 03;break ;
    ......

为什么碰巧使用 break it's C 语法

https://softwareengineering.stackexchange.com/questions/162574/why-do-we-have-to-use-break-in-switch

我有一点建议可以改进你的代码

 var d = new Date();
 var da = d.getDate();
 var monb = d.getMonth()+1;
 var yr = d.getFullYear();

 slashDate = monb + "/" + da + "/" + yr;

 document.getElementById('titleDate').innerHTML = slashDate; 

http://jsfiddle.net/q0mfds0t/3/