How to judge the Data Type in javascript

Source: Internet
Author: User

In js, there are N data types. Here we will introduce the commonly used data type judgment methods, including Number ). Including integer, floating point, Boolean, String, array, null, Undefined, etc.

Let's take a look at one of my interview questions.


During the interview last week, the examiner asked me how js judges that the data type of a variable is an Array. The typeof in js cannot distinguish Array from Object. This is a question of js. That is to say:

Typeof [] = 'object'; // The true method for judging the array is as follows: (long line feed is too long. You will check it)

The Code is as follows: Copy code

If (a & typeof a = 'object' & typeof a. length = 'number '&&
! A. propertyIsEnumerable ('length ')))
{
Alert ("a is an array ");
}

Well, I don't know what you understand. If you don't understand it, let's take a look.

1. Data Types in JS.

1. Number ). Including integers and floating-point numbers.
2. Boolean ).
3. String type (String ).
4. Object ).
5. Array ).
6. Null ).
7. Undefined ).

2. Determine the Data Type of a variable.

1. number ).
The commonly used judgment method is

The Code is as follows: Copy code
Function isNumber (val)
{
Return typeof val = 'number ';
}

But in some cases, this will not work. For example

Var;
Document. write (isNumber (parseInt ()));
True is printed here, but actually the variable a is NaN, which cannot be used for numerical operations.
So the above function can be modified

The Code is as follows: Copy code
Function isNumber (val)
{
Return typeof val = 'number' & isFinite (val );
}

The isFinite () function is provided by js and filters NaN and Infinity out.
In addition, to determine whether the variable is NaN, you can use isNaN (), which returns a Boolean value.

2. boolean, string, and Undefined ).
These three types are relatively simple and can be directly used

The Code is as follows: Copy code
Typeof val = 'boolean'
Typeof val = 'string'
Typeof val = 'undefined'

You can.

3. Object and Null ).
When the variable is Null, typeof also returns the object, so the Object cannot be directly used
Typeof judgment. This should be the case

The Code is as follows: Copy code
Function isObj (str)
{
If (str = null | typeof str = 'undefined ')
{
Return false;
}
Return typeof str = 'object ';
}

To determine the null value, use val = null. Be sure to use all.
4. Array ).
The array type cannot be determined by typeof. Because if the variable is of the array type, typeof returns the object.
There are two methods to determine the array type.

The Code is as follows: Copy code

Function isArray (arr)
{
Return Object. prototype. toString. apply (arr) = '[object Array]';
}
// Or
Function isArray (arr)
{
Return arr. constructor === Array;
}


Next, we will share some common functions for verifying data types.

The Code is as follows: Copy code

*********************** 1. Verification class *****************************/
// Whether the object exists
Function isObj (str)
{
If (str = null | typeof (str) = 'undefined ')
Return false;
Return true;
}
// Remove spaces from the string
Function strTrim (str)
{
If (! IsObj (str ))
Return 'undefined ';
Str = str. replace (/^/s + |/s + $/g ,'');
Return str;
}
/********************** 1. digit verification ************** ****************/
// 1. 1 integer
// Integer or empty
Function isIntOrNull (str ){
If (! IsObj (str) // determines whether an object exists
Return 'undefined ';
Return isNull (str) | isInt (str );
}
// It must be an integer
Function isInt (str ){
Var reg =/^ (-|/+ )? /D + $ /;
Return reg. test (str );
}
// 1.2 decimal places
// Decimal or empty
Function isFloatOrNull (str ){
If (! IsObj (str) // determines whether an object exists
Return 'undefined ';
If (isInt (str ))
Return true;
Return isNull (str) | isFloat (str );
}
// It must be a decimal number.
Function isFloat (str ){
If (isInt (str ))
Return true;
Var reg =/^ (-|/+ )? /D +/./d * $ /;
Return reg. test (str );
}
// 1.3 digit size judgment
// The number I cannot be greater than the number y
Function iMinY (I, y ){
If (! IsObj (I) |! IsObj (y) // determines whether an object exists
Return 'undefined ';
If (! (IsFloat (I) & isFloat (y )))
Return 'comparison must be numeric type'
If (I <= y)
Return true;
Return false;
}
// The number I cannot be less than the number y
Function iMaxY (I, y ){
If (! IsObj (I) |! IsObj (y) // determines whether an object exists
Return 'undefined ';
If (! (IsFloat (I) & isFloat (y )))
Return 'comparison must be numeric type'
If (I> = y)
Return true;
Return false;
}
/********************** 1. digit verification ************** ****************/

/********************* 2 time class verification ************* *****************/
// 2.1 for a short time, such as (13:04:06)
Function compute timecheck (str)
{
If (! IsObj (str) // determines whether an object exists
Return 'undefined ';
Var a = str. match (/^ (/d {1, 2 })(:)? (/D {1, 2})/2 (/d {1, 2}) $ /);
// Var a = str. match (/^/d {1, 2}:/d {1, 2}:/d {1, 2} $ /);
If (a = null)
{
Alert ("the input parameter is not in the time format ");
Return false;
}
If (a [1]> 24 | a [3]> 60 | a [4]> 60)
{
Alert ("Time Format incorrect ");
Return false
}
Return true;
}
// 2.2 Short date, such)
Function shorDateCheck (str)
{
Var r = str. match (/^ (/d {1, 4}) (-| //) (/d {1, 2})/2 (/d {1, 2}) $ /);
If (r = null)
Return false;
Var d = new Date (r [1], r [3]-1, r [4]);
Return (d. getFullYear () = r [1] & (d. getMonth () + 1) = r [3] & d. getDate () = r [4]);
}
// 2.3 long time, such as (13:04:06)
Function longDateCheck (str)
{
Var reg =/^ (/d {1, 4}) (-| //) (/d {1, 2})/2 (/d {1, 2 }) (/d {1, 2}) :(/d {1, 2}) :(/d {1, 2}) $ /;
Var r = str. match (reg );
If (r = null)
Return false;
Var d = new Date (r [1], r [3]-1, r [4], r [5], r [6], r [7]);
Return (d. getFullYear () = r [1] & (d. getMonth () + 1) = r [3] & d. getDate () = r [4] & d. getHours () = r [5] & d. getMinutes () = r [6] & d. getSeconds () = r [7]);
}
// 2.4 only supports year and month. Such as (2003-05, or 2003-5)
// 2.5 only hours and minutes, such)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.