最常用的判断方法:typeof
var a=‘isString‘;var b=121221;var c=[1,2,3];var d=new Date();var e=function(){console.log(‘12‘);};var f=function(){this.name=‘22‘;};var g=null;var h=undefined;var i=true;console.log(typeof b) =======> numberconsole.log(typeof a) =======> stringconsole.log(typeof h) =======> undefinedconsole.log(typeof i) =======> booleanconsole.log(typeof c) =======> objectconsole.log(typeof d) =======> objectconsole.log(typeof g) =======> objectconsole.log(typeof e) =======> function console.log(typeof f) =======> function
总结 在 JavaScript 里使用 typeof 来判断数据类型,只能区分基本类型,即 “number”,”string”,”undefined”,”boolean”,”object” 五种。
对于数组、函数、对象来说,其关系错综复杂,使用 typeof 都会统一返回 “object” 字符串。
判断已知对象类型的方法 instanceof
console.log(c instanceof Array) =======> trueconsole.log(d instanceof Date) =======> trueconsole.log(f instanceof Function) =======> trueconsole.log(f instanceof function) =======> false
注意:instanceof 后面一定要是对象类型,并且大小写不能错,该方法适合一些条件选择或分支。
根据对象的constructor判断: constructor
console.log(c.constructor === Array) ----------> trueconsole.log(d.constructor === Date) -----------> trueconsole.log(e.constructor === Function) -------> true注意: constructor 在类继承时会出错eg:function A(){};function B(){};A.prototype = new B(); //A继承自Bvar aObj = new A();console.log(aObj.constructor === B) -----------> true;console.log(aObj.constructor === A) -----------> false;而instanceof方法不会出现该问题,对象直接继承和间接继承的都会报true:console.log(aObj instanceof B) ----------------> true;言归正传,解决construtor的问题通常是让对象的constructor手动指向自己:aObj.constructor = A; //将自己的类赋值给对象的constructor属性console.log(aObj.constructor === A) -----------> true;console.log(aObj.constructor === B) -----------> false; //基类不会报true了;
繁琐的方法: prototype
在JavaScript中,想要判断某个对象值属于哪种内置类型,最靠谱的做法就是通过Object.prototype.toString方法.
console.log(Object.prototype.toString.call(a) === ‘[object String]’) -------> true;console.log(Object.prototype.toString.call(b) === ‘[object Number]’) -------> true;console.log(Object.prototype.toString.call(c) === ‘[object Array]’) -------> true;console.log(Object.prototype.toString.call(d) === ‘[object Date]’) -------> true;console.log(Object.prototype.toString.call(e) === ‘[object Function]’) -------> true;console.log(Object.prototype.toString.call(f) === ‘[object Function]’) -------> true;
jquery.type()
测试中所用到的 jquery: verson 3.0.0
console.log(‘number:‘, jQuery.type(2));console.log(‘string:‘, jQuery.type(‘test‘));console.log(‘true or false :‘, jQuery.type(true));console.log(‘undefined :‘, jQuery.type(undefined));console.log(‘‘, jQuery.type());console.log(‘null:‘, jQuery.type(null));console.log(‘new Date():‘, jQuery.type(new Date()));console.log(‘Function:‘, jQuery.type(function() {}));console.log(‘Array:‘, jQuery.type([]));console.log(‘Object:‘, jQuery.type({}));console.log(‘new Error():‘, jQuery.type(new Error()));console.log(‘reg:‘, jQuery.type(/test/));console.log(‘ES6 新语法:symbol:‘, jQuery.type(Symbol()));
[参考链接]:https://www.cnblogs.com/dushao/p/5999563.html