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 "){...}