js 判断数据类型的方法

js 判断数据类型的方法 胡小邦

js 判断数据类型的方法

判断js中的数据类型有一下几种方法:typeof、instanceof、 constructor、 prototype、 $.type()/jquery.type()。

举个例子:

var a = "iamstring.";
var b = 222;
var c= [1,2,3];
var d = new Date();
var e = function(){alert(111);};
var f = function(){this.name="22";}; 

1、最常见的判断方法:typeof

alert(typeof a)  ----> string
alert(typeof b)  ----> number
alert(typeof c)  ----> object
alert(typeof d)  ----> object
alert(typeof e)  ----> function
alert(typeof f)  ----> function

其中typeof返回的类型都是字符串形式,需注意,例如:

alert(typeof a == "string") -----> true
alert(typeof a == String) ----> false

typeof 可以判断function的类型;在判断除Object类型的对象时比较方便。


2、判断已知对象类型的方法: instanceof

alert(c instanceof Array) ----> true
alert(d instanceof Date)
alert(f instanceof Function) ----> true
alert(f instanceof function) ----> false

注意:instanceof 后面一定要是对象类型,并且大小写不能错,该方法适合一些条件选择或分支。 


3、根据对象的constructor判断: constructor

alert(c.constructor === Array) ----------> true
alert(d.constructor === Date) -----------> true
alert(e.constructor === Function) -------> true

注意: constructor 在类继承时会出错


5、万能的方法:jquery.type()

如果对象是undefined或null,则返回相应的“undefined”或“null”。

jQuery.type( undefined ) === "undefined"
jQuery.type() === "undefined"
jQuery.type( window.notDefined ) === "undefined"
jQuery.type( null ) === "null"

一切都将返回它的类型“object”。


注:通常情况下用typeof 判断就可以了,遇到预知Object类型的情况可以选用instanceof或constructor方法。

同学们如果有什么不足请告诉我~

还能输出{{restrictNumber}}个字符  
  • {{reply.author}}

    {{CommonUtil.formateDate(reply.ac_CommentDate).shortTime}}
  • 回复了{{Comments.author}} :