基本数据类型:String,Number,Boolean,Symbol,undefined,Null引用类型:Object数组函数判断数据类型的方法:js中判断数据类型的方法有以下几种:typeof,instanceof,constructor,prototype,$.type()/jquery.type(),然后主要比较这几个方法的异同点。这里有几个例子:vara="iamstring.";varb=222;varc=[1,2,3];vard=newDate();vare=function(){alert(111);};varf=function(){this.name="22";};1.最常见的判断方式:typeofalert(typeofa)------------>stringalert(typeofb)------------>numberalert(typeofc)----------->objectalert(typeofd)---------->objectalert(typeofe)---------->functionalert(typeoff)---------->functionwheretypeof返回的类型都是字符串形式,请注意例如:alert(typeofa=="string")------------->truealert(typeofa==String)-------------->false另外typeof可以判断函数的类型;在判断Object类型以外的对象时更方便。2.判断已知对象类型的方法:instanceofinstanceof原理:instanceof检测一个对象A是否是另一个对象B的实例的原理是检查对象B的原型指向的对象是否在[[prototype]]对象链A。如果存在则返回true,如果不存在则返回false。但是有一种特殊情况,当对象B的原型为null时,会报错(类似于空指针异常)。alert(cinstanceofArray)-------------->truealert(dinstanceofDate)alert(finstanceofFunction)---------->truealert(finstanceoffunction)---------->false3.根据对象的构造函数判断:constructoralert(c.constructor===Array)---------->truealert(d.constructor===Date)---------->truealert(e.constructor===Function)------>true注意:类继承时constructor会报错例如:函数A(){};函数B(){};A.prototype=newB();//A继承自BvaraObj=newA();alert(aobj.constructor===B)----------->真;alert(aobj.constructor===A)---------->false;言归正传,解决构造函数问题通常是让对象的构造函数手动指向自身:aobj。构造函数=A;//将自己的类赋值给对象的constructor属性alert(aobj.constructor===A)---------->true;alert(aobj.constructor===B)---------->false;//基类不会报true;4.通用但繁琐的方法:prototypealert(Object.prototype.toString.call(a)==='[objectString]')------>true;alert(Object.prototype.toString.call(b)==='[objectNumber]')------>true;alert(Object.prototype.toString.call(c)==='[objectArray]')------->true;alert(Object.prototype.toString.call(d)==='[objectDate]')------>true;alert(Object.prototype.toString.call(e)==='[objectFunction]')------>true;alert(Object.prototype.toString.call(f)==='[objectFunction]')------->真;大小写不能写错,比较麻烦,但总比一般好5.无敌通用方法jquery.type()如果对象是undefined或null,则返回对应的“undefined”或“null”。jQuery.type(undefined)==="undefined"jQuery.type()==="undefined"jQuery.type(window.notDefined)==="undefined"jQuery.type(null)==="null"如果对象有一个内部的[[Class]],与浏览器的内置对象[[Class]]相同,我们返回相应的[[Class]]名称。jQuery.type(true)==="boolean"jQuery.type(3)==="number"jQuery.type("test")==="string"jQuery.type(function(){})==="function"jQuery.type([])==="array"jQuery.type(newDate())==="date"jQuery.type(newError())==="error"//作为jQuery1.9jQuery.type(/test/)==="regexp"其他一切都将返回其类型“object”。通常使用typeof判断即可。在预测Object类型的情况下,可以使用instanceof或者constructor方法。如果没有办法,就使用$.type()方法。
