我无法将此伪代码语句转换为javascript我是javascript的新手,我对拼写字符串感到困惑,我想确保我在正确的轨道上
// Date validation function
Function Boolean isValidDateFormat(String str)
// Declare variables
Declare String mm, dd, yyyy // month, day, year
Declare Boolean result = True // valid date format
// Check that length of string is 10
If length(str) != 10 Then
result = False
End If
// Check that third and sixth characters are slashes
If substring(str,2,1) != "/" Or
substring(str,5,1) != "/" Then
result = False
End If
// Separate string into parts
// Check that all entries are numeric
mm = substring(str,0,2) // month
dd = substring(str,3,2) // day
yyyy = substring(str,6,4) // year
If Not isNumeric(mm) Or Not isNumeric(dd)
Or Not isNumeric(yyyy) Then
result = False
End If
// Check that month is between 1 and 12
// and day is between 1 and 31
If (mm < 1 Or mm > 12) Or (dd < 1 Or dd > 31) Then
result = False
End If
Return result
End Function
这是我的javascript翻译
function isValidDateFormat(String str){
return false;
if (str.length <10)
return false;
dd= substr[0];
mm= substr[3];
yyyy= substr[6];
if substr [2]!= "/";
substr [5]!= "/";
return false;
if (mm < 1 || mm > 12)
return false;
else if (dd < 1 || dd> 31)
return false;
答案 0 :(得分:1)
这是你的功能:
function isValidDateFormat(str){
var mm, dd, yyyy;
if(str.length != 10){
return false;
}
if(str.charAt(2) != "/" || str.charAt(5) != "/"){
return false;
}
mm = str.substring(0,2);
dd = str.substring(3,5);
yyyy = str.substring(6,10);
if(parseInt(mm) != parseInt(mm) ||
parseInt(dd) != parseInt(dd) ||
parseInt(yyyy) != parseInt(yyyy) ||
parseFloat(yyyy) % 1 != 0){
return false;
}
if(parseInt(mm) < 1 ||
parseInt(mm) > 12 ||
parseInt(dd) < 1 ||
parseInt(dd) > 31){
return false;
}
return true;
};
console.log("is foobarbaz valid? " + isValidDateFormat("foobarbaz"));
console.log("is 09-21-1989 valid? " + isValidDateFormat("09-21-1989"));
console.log("is 88/88/8888 valid? " + isValidDateFormat("88/88/8888"));
console.log("is 09/21/19.9 valid? " + isValidDateFormat("09/21/19.9"));
console.log("is 04/12/1967 valid? " + isValidDateFormat("04/12/1967"));
有多种方法可以检查字符串是否包含数字,在这里我使用a != a
来捕获NaN。
注意:这将使用您的原始伪代码返回true:
console.log(isValidDateFormat("09/21/19.9"));
因此,您必须更改代码以检查字符串是否包含仅数字(因为,毕竟19.9是数字...)。一种方法是检查余数:
parseFloat(yyyy) % 1 != 0