1.typeof
TypeOf can only judge the basic types, number, String, Boolean, Undefined, and object,function;
typeof0;//Number ;typeof true;//Boolean;typeofUndefined//undefined;typeof"Hello World"//string;typeof function(){};//function;typeof NULL;//Objecttypeof{};//object;typeof[];//Object
As we can see from the above example, the TypeOf object and array all return object, so it cannot distinguish between objects and arrays.
2.instanceof
var a=instanceof Object //truea intanceof Array // false var b=instanceof Array //trueinstanceof //true
Because the array belongs to one of the objects, the array instanceof object, which is also true.
var c= ' abc 'instanceof//falsevar d=new instanceof String //true
Instanceof cannot distinguish between the base type string and the Boolean, unless it is a string object and a Boolean object. As shown in the example above.
3.constructor
var o={};o.constructor==object //truevar arr=[]; Arr.constructor==array //true//false
You can see that constructor can distinguish between array and object.
var n=true; n.constructor==boolean //truevar num=1; Num.constructor==number //truevar str= ' Hello World '; str.constructor ==string //True
var num=new number ();
Num.constructor==number//true
Note, however, that the constructor property can be modified, causing incorrect results to be detected
function Person () { }function Student () { new person (); var New Student (); Console.log (John.constructor// false// true
In addition to undefined and null, other types of variables can use constructor to determine the type. 4.object.prototype.tostring.call ()---------most useful
Object.prototype.toString.call (123)//"[Object number]" Object.prototype.toString.call (' str ')//"[Object String]" Object.prototype.toString.call (true)//"[Object Boolean]" Object.prototype.toString.call ({})//"[Object Object]" Object.prototype.toString.call ([])//"[Object Array]"
Encapsulates a method for judging arrays and objects
function typeobj (obj) { var type=Object.prototype.toString.call (obj); if (type== ' [object array] ') { return ' array '; } ElseIf (Type= = ' [Object object] ') {return ' object '; } Else { return ' obj is not object or array '} }
When the Object.prototype.toString method is called, the following steps are performed:
1. Gets the class name (object type) of the object.
[[Class]] is an intrinsic property, and all objects (native and host objects) have that property. In the specification, [[class]] is defined as:
Internal property, [[Class]] A string value that indicates the type of the object.
2. Then combine [the name of the object type obtained by] into a string
3. Returns the string "[Object Array]".
$.type interface in 5.jQuery
$.type (obj);
$.isarray (obj);
$.isfunction (obj);
$.isplainobject (obj);
$.type ([]) //array//true$.isfunction (function// True//true//false
JS Judging Object Type