Recent projects have encountered some of the JavaScript data types of judgment processing, the Internet to find information, and personally verify the various data types of judgment, here to do a summary!
The data type in JS
1. Numeric (number): Includes integers, floating-point numbers.
2. Boolean Type (Boolean)
3. String type
4. Objects (object)
5. Arrays (Array)
6. Null value (NULL)
7. Undefined (Undefined)
Second, determine the data type of a variable
1, numeric type (number)
The more common methods of judging are:
function Isnumber (val) { returntypeof'number' ;} var A;isnumber (parseint (a));
But in some cases not, such as the above to judge A, is true, this is obviously wrong:
The variable A is actually Nan, and it cannot be used for numeric operations. So the above function can be modified to:
function Isnumber (val) { returntypeof'number' & & Isfinite (val);}
This is correct, by the way, by introducing the JavaScript isfinite () function, theisfinite () function is used to check if the parameter is infinite, and if number is a finite digit (or convertible to a finite number), then true is returned. Otherwise, if number is NaN (not a number), or positive, negative infinity, then false is returned.
2. Boolean Type (Boolean)
Boolean type judgment is relatively simple, can be judged by the following methods:
// The judging variable val is not a Boolean type function Isbooleantype (val) { returntypeof val = = ="boolean" ;}
3. Strings (String)
The judgment of the string type is relatively simple and can be judged by the following methods:
// The judging variable val is not a string type function Isstringtype (val) { returntypeof val = = = ="string" ;}
4. Undefined (Undefined)
Undefined judgments are relatively simple and can be judged by the following methods:
// Judging the variable val is not undefined function isundefined (val) { returntypeof val = = ="undefined" ;}
5. Objects (object)
Because when a variable is null, typeof also returns object, so object cannot be judged directly with TypeOf. This should be the case:
// The judging variable is not of type Object function Isobj (str) { ifnulltypeof'undefined' ) { returnfalse; } return typeof ' Object ' ;}
6, null value (NULL)
Determine null with val = = = NULL
// determine if the variable is not NULL function IsNull (val) { return null;}
7. Arrays (Array)
The array type cannot be judged by typeof. Because when a variable is an array type, typeof returns an object.
Here are two ways to determine the array type:
/*The judgment variable arr is not an array method one*/function IsArray1 (arr) {returnObject.prototype.toString.apply (arr) = = ='[Object Array]';}/*determine if the variable arr is array method two*/function IsArray2 (arr) {if(arr = = =NULL||typeofarr = = ='undefined'){ return false; } returnArr.constructor = = =Array;}
JavaScript Judging data Type summary