Why doesn't my return
within the IF work?
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(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. Try learning about regex
or even a foreach
would do the job.
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). Note that Number.isInteger(value)
will return false for any string, even if there is a number as string. 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.
another way is to check using a regular expression test
replace: str1[0].isInteger === true &&
with: /[0-9]/.test(str1[0]) &&
This will check if the string provided is a digit between 0 and 9
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.