判断js中的数据类型有一下几种方法:typeof、instanceof、 constructor、 prototype,接下来主要比较一下这几种方法的异同
下面先准备几个例子:
var a = "iamstring.";var b = 222;var c= [1,2,3];var d = new Date();
var e = {a:1,b:2};var f = function(){alert(111);};
1、常用的类型判断方法:typeof
console.log(typeof a) ??------------> stringconsole.log(typeof b) ??------------> numberconsole.log(typeof c) ??------------> objectconsole.log(typeof d) ??------------> objectconsole.log(typeof e) ??------------> objectconsole.log(typeof f) ??------------> function其中typeof返回的类型都是字符串形式,需注意,例如:alert(typeof a === "string") -------------> truealert(typeof a == String) ---------------> false另外typeof 可以判断function的类型,判断function类型时比较方便。
2、判断已知是对象类型的方法: instanceof
console.log(c instanceof Array) ---------------> trueconsole.log(d instanceof Date) ---------------> trueconsole.log(e instanceof Object) ------------> trueconsole.log(f instanceof Function) ------------> true注意:instanceof 后面一定要是对象类型,并且大小写不能错,该方法适用于typeof不能判断的部分引用数据类型的情况。
3、根据对象的constructor判断: constructor
alert(c.constructor === Array) ----------> truealert(d.constructor === Date) -----------> truealert(e.constructor === Object) -------> truealert(f.constructor === Function) -------> true注意:类名也是要用大写开头,constructor 在类继承时会出错eg: ?????function A(){}; ?????function B(){}; ?????A.prototype = new B(); //A继承自B ?????var aobj= new A(); ?????alert(aobj.constructor === B) -----------> true; ?????alert(aobj.constructor === A) -----------> false; ?????alert(aobj.constructor === Object) -----------> false; ?//因为不是直接继承该类而instanceof方法不会出现该问题,对象直接继承和间接继承的都会报true: ?????alert(aobj instanceof A) ----------------> true; ?????alert(aobj instanceof B) ----------------> true; ?????alert(aobj instanceof Object) ----------------> true;这种情况下,解决construtor的问题通常是让对象的constructor手动指向自己: ?????aobj.constructor = A; //将自己的类赋值给对象的constructor属性 ?????alert(aobj.constructor === A) -----------> true; ?????alert(aobj.constructor === B) -----------> false; //基类不会报true了; ??????????alert(aobj.constructor === Object) -----------> false; //基类不会报true了; 所以,实例的constructor属性为它直接继承的类或者手动设置的constructor属性所指向的类 ????
3、通用方法: prototype调用toString()方法
alert(Object.prototype.toString.call(a) === ‘[object String]’) -------> true;alert(Object.prototype.toString.call(b) === ‘[object Number]’) -------> true;alert(Object.prototype.toString.call(c) === ‘[object Array]’) -------> true;alert(Object.prototype.toString.call(d) === ‘[object Date]’) -------> true;alert(Object.prototype.toString.call(e) === ‘[object Object]’) -------> true;alert(Object.prototype.toString.call(f) === ‘[object Function]’) -------> true;万能方法
总结:
通常情况下基本数据类型用typeof 判断就可以了,遇到预知Object类型的情况可以选用instanceof或constructor方法。
js数据类型的判断
原文地址:https://www.cnblogs.com/leelam/p/9389849.html