简体   繁体   中英

Javascript validation using Number object

concider the following code:

var postValue = "99";
var number = new Number(postValue); //also tried var number = parseInt(postValue);
if (isNaN(number)) { 
              alert('please enter a number');
                        }

How come isNan(number) in both cases is false?

isNAN = "is NOT a number". This means that, if isNaN(number) === false , then number IS a number:

var postValue = "99";
var number = parseInt(postValue);
if (isNaN(number)) { 
    alert('please enter a number');
}

parseInt() will convert your string to an integer. To do so, it reads characters from the left of the string to find as many number characters as it can, then returns that number.

In this case, since "99" is all numeric characters, the result is the number 99. Which is very clearly "not-not a number" and therefore isNaN returns false.

isNaN will return true if the input string starts with something that isn't a digit.

isNaN() : Is Not a Number, would return false when the argument is not a NUMBER. Which is the case for you code. You always get a number in both the cases.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM