gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:18:31 25 4
gpt4 key购买 nike

我有一个关于在 Javascript 中使用 IF 语句与 SWITCH 的可能非常简单的问题。我试图以“月/日/年”的格式将当前日期添加到我的页面,其中“月”是一个像“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语句,则开关将继续执行下一个案例,即使该案例与给定开关的条件不匹配。在这种情况下,如果没有break语句,它总是为monb返回12。

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

关于Javascript - 使用 "IF"与 "SWITCH"将 toDateString 月份从文本字符串解析为数字字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29356871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com