Those who know js know that there is a typeof used to judge various data types. There are two ways to write it: typeof xxx, typeof(xxx)
The following example:
typeof 2 output number
typeof null output object
typeof {} output object
typeof [] output object
typeof (function(){}) output function
typeof undefined output undefined
typeof '222' output string
typeof true output boolean
This includes five data types in js number string boolean undefinedobject and function type function
After seeing this, you will definitely ask: How do I distinguish between objects, arrays and null?
Next we will use another weapon: Object.prototype.toString.call
This is a native prototype extension function of the object, used to more accurately distinguish data types.
Let's try this fun:
var gettype=Object.prototype.toString
gettype.call('aaaa') output [object String]
gettype.call(2222) Output [object Number]
gettype.call(true) output [object Boolean]
gettype.call(undefined) output [object Undefined]
gettype.call(null) output [object Null]
gettype.call({}) output [object Object]
gettype.call([]) output [object Array]
gettype.call(function(){}) output [object Function]
Seeing this, we solved the problem just now.
In fact, there are many types of judgments in js
[object HTMLDivElement] div object,
[object HTMLBodyElement] body object,
[object Document](IE) or
[object HTMLDocument] (firefox, google) ......
The judgment of various dom nodes is used when we write plug-ins.
The methods that can be encapsulated are as follows:
var gettype=Object.prototype.toStringvar utility={isObject:function(o){ return gettype.call(o)=="[object Object]"; }, isArray:function(o){ return gettype.call(o)=="[object Array]"; }, isNULL:function(o){ return gettype.call(o)=="[object Null]"; }, isDocument:function(){ return gettype.call(o)=="[object Document]"|| [object HTMLDocument]; } ........}The above simple method (recommended) for judging various data types by js is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.