We know that JavaScript is a weak type of language, and that everything in JavaScript is essentially an object. So, how to do object type checking in JavaScript is a very important topic.
Here, I will describe two methods that are commonly used in JS for type detection.
The first approach is to use the "typeof" operator, which may be known to everyone. The result of using it for type detection is one of the following six strings: "Number", "Boolean", "Object", "number", "Function", "string". Well, with this operator, most of the object types can be detected, but there is one exception: that is when using arrays. JavaScript itself is confusing for arrays and objects, and the typeof operator reports that the types of arrays and objects are "object", so JavaScript does not yield a good mechanism for distinguishing between arrays and objects.
For example:
var arr=[1,2,3,4,5]var obj={"name": "Xiaoming", "Sex": "Nan"};alert (typeof arr)// Return "Object"alert (typeof obj)// Return "Object"
So, how do we judge this particular situation?
Here is the second common way to do type checking: the "constructor" property.
In JavaScript, any object has a constructor property that refers to the original function that was used to construct the object.
The following example code illustrates the use of this approach:
var num=11,str= "abc", obj={num:11},arr=[1,2,3];alert (num.constructor===number); // truealert (str.constructor===string); // truealert (obj.constructor===object); // truealert (Arr.constructor===array); // true
As you can see, when using constructor, the array returned is no longer an object, but an array of distinct meanings.
The following table shows the results of type checking for different types of objects using both of these methods.
Variable typeof variable variable. construtor
{an: "Object"} Object Object
["An", "array"] Object array
function () {} function function
"A string" string string
Number number
True Boolean Boolean
New User () object User
It is important to note that the result returned by thetypeof operator is a string , and the result returned by the constructor property is an object .
So, through the above just, we can define our own Is_array function to check the array:
var is_array=function() { return value && typeof value=== ' object ' && value.constructor= = =Array;}
JavaScript: Object type checking