The following small series will provide you with a simple method (recommended) to judge various data types in js ). I think this is quite good. Now I will share it with you and give you a reference. Let's take a look at it together. We all know about js. There is a typeof to judge various data types. There are two ways to write: typeof xxx, typeof (xxx)
Example:
Typeof 2 output number
Typeof null Output object
Typeof {} output object
Typeof [] Output object
Typeof (function () {}) Output function
Typeof undefined output undefined
Typeof '200' output string
Typeof true outputs boolean
Five data types in js are included in this section: number string boolean undefinedobject and function type function.
Here you will certainly ask: how can I differentiate objects, arrays, and null?
Next we will use another tool: Object. prototype. toString. call
This is a native prototype Extension function of the object, which is used to distinguish data types more accurately.
Let's try this fun:
Var gettype = Object. prototype. toString
Gettype. call ('aaa') Outputs [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]
We have solved the problem.
In fact, there are many types of judgment in js
[Object HTMLDivElement] p object,
[Object HTMLBodyElement] body object,
[Object Document] (IE) or
[Object HTMLDocument] (firefox, google )......
Various dom node judgments are used when we write plug-ins.
The encapsulation method is as follows:
var gettype=Object.prototype.toString var utility={ isObj: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 simple method (recommended) for judging various data types in js is all the content shared by Alibaba Cloud xiaobian. I hope to give you a reference and support for PHP.
For more articles about how to judge various data types in js, please refer to the PHP Chinese website!