使用 switch 命令进行日期验证不起作用
我正在编写一个简单的函数来验证日期。问题是 switch 运算符似乎不匹配任何内容,并且 maxDay
的值仍然为 0。如果我使用 if
语句,我不会有任何问题。
function validateDateFormat(day,month,year) {
alert(month); // this was to ensure month was correct and it is!!
var maxDay = 0;
switch(month)
{
case 01 :
case 03 :
case 05 :
case 07 :
case 08 :
case 10 :
case 12 : maxDay = 31; break;
case 04 :
case 06 :
case 09 :
case 11 : maxDay = 30; break;
case 02 : if(year%4 == 0) maxDay = 29;
else maxDay = 28;
break;
//default : return " Invalid month -"; break;
}
alert(maxDay);
if(day > maxDay) {return " Invalid day -";}
return "";
}
I'm writing a simple function to validate a date. The problem is it seems that the switch operator does not match anything and the value of maxDay
remains 0. If I use if
statements I don't have any problem.
function validateDateFormat(day,month,year) {
alert(month); // this was to ensure month was correct and it is!!
var maxDay = 0;
switch(month)
{
case 01 :
case 03 :
case 05 :
case 07 :
case 08 :
case 10 :
case 12 : maxDay = 31; break;
case 04 :
case 06 :
case 09 :
case 11 : maxDay = 30; break;
case 02 : if(year%4 == 0) maxDay = 29;
else maxDay = 28;
break;
//default : return " Invalid month -"; break;
}
alert(maxDay);
if(day > maxDay) {return " Invalid day -";}
return "";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我强烈怀疑根本问题是您提供字符串作为
validateDateFormat
的参数。如果是这样,那么使用if
时的行为肯定会不同于使用switch
时的行为。例如,假设您要编写以下内容:这将警告
true
因为==
(双等于)会触发对num
中的字符串进行强制转换在执行比较之前将其转换为数字。但是,这不会发出任何警报:...因为
switch
使用更严格的===
(三等号)运算符,该运算符不执行类型强制。然而,这确实会警告
true
:...因为我们现在正在比较字符串。
因此,要修复代码,您需要传递实际数字,或修改函数以比较字符串。
注意: ECMAScript 规范第 12.11 节。
I strongly suspect the root issue is that you're providing strings as the arguments to
validateDateFormat
. If so, then the behavior can definitely be different when usingif
than when usingswitch
. For example, assume you were to write this:This will alert
true
because==
(double-equals) triggers coercion of the string innum
to a number before performing the comparison. However, this will alert nothing:...because
switch
uses the more strict===
(triple-equals) operator, which does not perform type-coercion.This, however, does alert
true
:...because we're now comparing strings.
So, to fix your code you need to either pass actual numbers, or modify the function to compare strings.
Note: The
switch
behavior is covered in section 12.11 of the ECMAScript spec.您不应在号码前加上
0
前缀;这会导致数字文字被解释为八进制。由于08
不是有效的八进制数,因此您的脚本可能会生成运行时错误。You should not prefix your numbers with a
0
; that causes the numeric literal to be interpreted as octal. Since08
is not a valid octal number, your script may be generating a runtime error.