[英]Checking if a character (as a string) is digit with isInteger does not work
Why doesn't my return
within the IF work?为什么我在 IF 内的return
不起作用?
function telephoneCheck(str) {
var a;
let result = false;
let str1 = str.split("");
if (
str1[0].isInteger === true &&
str1[1].isInteger === true &&
str1[2].isInteger === true &&
str1[3] === "-" &&
str1[4].isInteger === true &&
str1[5].isInteger === true &&
str1[6].isInteger === true &&
str1[7] === "-" &&
str1[8].isInteger === true &&
str1[9].isInteger === true &&
str1[10].isInteger === true &&
str1[11].isInteger === true
) {
return true;
}
}
telephoneCheck("555-555-5555");
Your code is not working because Number.isInteger()
should be used as follows:您的代码不起作用,因为Number.isInteger()
应按如下方式使用:
Number.isInteger(5) //true
Number.isInteger(4.3) //false
Numbers.isInteger('5') //false
Now, for your code to work, you need to check this way现在,要使您的代码正常工作,您需要以这种方式进行检查
Number.isInteger(parseInt(str[i])) === true //which is not really necessary
Number.isInteger(parseInt(str[i])) //is enough
While this works, there are more neat ways to write the function you need.虽然这可行,但还有更简洁的方法来编写您需要的 function。 Try learning about regex
or even a foreach
would do the job.尝试学习regex
,甚至foreach
都可以完成这项工作。
If I were you, I would use isNaN
to check if str1[index] is a number, since it also checks if there is a number as string (which is the case in your example).如果我是你,我会使用isNaN
检查 str1[index] 是否是一个数字,因为它还会检查是否有一个数字作为字符串(在你的例子中就是这种情况)。 Note that Number.isInteger(value)
will return false for any string, even if there is a number as string.请注意, Number.isInteger(value)
将为任何字符串返回 false,即使有一个数字作为字符串。 Check my suggestion below:在下面检查我的建议:
function telephoneCheck(str) {
let str1 = str.split("");
if (
isNumber(str1[0]) &&
isNumber(str1[1]) &&
isNumber(str1[2]) &&
str1[3] === "-" &&
isNumber(str1[4]) &&
isNumber(str1[5]) &&
isNumber(str1[6]) &&
str1[7] === "-" &&
isNumber(str1[8]) &&
isNumber(str1[9]) &&
isNumber(str1[10]) &&
isNumber(str1[11])
) {
return true;
}
}
function isNumber(input) {
return !isNaN(input);
}
telephoneCheck("555-555-5555");
isInteger()
is a method of the Number() object, so your test to a string will not work, you could cast the string to a number but you might lose the meaning of the validation. isInteger()
是 Number() object 的一种方法,因此您对字符串的测试将不起作用,您可以将字符串转换为数字,但您可能会失去验证的含义。
another way is to check using a regular expression test另一种方法是使用正则表达式测试进行检查
replace: str1[0].isInteger === true &&
替换: str1[0].isInteger === true &&
with: /[0-9]/.test(str1[0]) &&
与:/[0-9]/.test( /[0-9]/.test(str1[0]) &&
This will check if the string provided is a digit between 0 and 9这将检查提供的字符串是否是 0 到 9 之间的数字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.