Javascript code that detects variable types

Source: Internet
Author: User

There are two common methods to check the variable type:
Method 1: typeof
Format: typeof variable
Usage: if (typeof variable = "type identifier "){...}
Below are some typeof values corresponding to common data types:
{An: "object"}: object
["An", "array"]: object
Function () {}: function
"A string": string
55: number
True: boolean
New User (): object

From the preceding table, we can see that when typeof is used to obtain the variable type, objects of arrays, objects, and custom classes are treated as objects, and Other types are checked normally. Therefore, it cannot determine whether it is an object, an array, or a User. Now we can use the second method for processing.

Method 2: constructor)
Format: variable. constructor
Usage: if (variable. constructor = "type identifier "){...}
{An: "object"}: Object
["An", "array"]: Array
Function () {}: Function
"A string": String
55: Number
True: Boolean
New User (): User

As shown in the preceding table, we can obtain the correct data types. Therefore, it is better to use the variable constructor to obtain the variable type.
However, sometimes this is more convenient:
If (typeof variable = "undefined "){...}

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.