We know that JavaScript is a weak type of language, and everything in Javascript is essentially an object. Therefore, it is very important to check the object type in JavaScript.
Here, I will introduce two methods that are frequently used in Js for type detection.
The first method is to use the "typeof" operator, which may be known to everyone. One of the following six strings is used for type detection: "Number", "Boolean", "object", "Number", "function ", "string ". Yes. We can detect the vast majority of object types using this operator. However, here is an exception: when using arrays. The difference between arrays and objects in Javascript itself is confusing. The typeof operator reports that arrays and objects are of the "object" type. Therefore, javaScript does not have a good yield mechanism for distinguishing arrays and objects.
For example:
VaR arr = [1, 2, 4, 5] <br/> var OBJ = {"name": "Xiaoming", "sex": "Nan "}; <br/> alert (typeof ARR) // returns "object" <br/> alert (typeof OBJ) // returns "object"
So how can we identify this special situation?
Here is the second common method for checking the type: "constructor" attribute.
In JavaScript, any object has a constructor attribute, which references the original function used to construct the object.
The following sample code illustrates the usage of this method:
VaR num = 11, STR = "ABC", OBJ = {num: 11}, arr = [1, 2]; <br/> alert (Num. constructor = number); // true <br/> alert (Str. constructor === string); // true <br/> alert (obj. constructor === object); // true <br/> alert (ARR. constructor === array); // true
As you can see, when using constructor, the array does not return an object, but an array with a clear meaning.
The following table shows the results of performing type checks on different types of objects using the preceding two methods.
Variable typeof variable. construtor
{An: "object"} object
["An", "array"] object Array
Function () {} function Function
"A string" string
55 number
True Boolean
New User () Object User
Note that,TypeofThe result returned by the operator isStringAndConstructorThe result returned by the property isObject.
Therefore, the above only means that we can define our own is_array function to check the array:
VaR is_array = function () {<br/> Return Value & <br/> typeof value = 'object' & <br/> value. constructor === array; <br/>}
In this way, this defect of JS can be effectively solved.