您好,欢迎访问一九零五行业门户网

js数据类型检测的4种方法

1.typeof
缺点:对null和array等类型的检测不是很方便
js代码  
typeof null; //object  
typeof []; //object  
2.instanceof
缺点:1.只适用于对象类型
        2.只要当前的这个类在实例的原型链上,检测出来的结果都是true
js代码  
123 instanceof number; //false  
null instanceof null; //typeerror  
null instanceof object; //false  
function a(){}  
function b(){}  
a.prototype=new b();  
var aobj=new a();  
aobj instanceof b;//true  
aobj instanceof a;//true  
 3.constructor
注意:在类继承时会出错
js代码  
function a(){};  
function b(){};  
a.prototype = new b();  
var aobj = new a();  
aobj.constructor === b; //true;  
aobj.constructor === a; //false;  
 4.自定义方法实现(比较通用)
js代码  
function gettype(o){  
  return object.prototype.tostring.call(o).slice(8,-1);  
}  
 测试:
js代码  
gettype(null); //null  
gettype(undefined); //undefined  
gettype([]); //array  
gettype({}); //object  
gettype(()=>{}); //function  
gettype(document.createelement('div')); //htmldivelement
其它类似信息

推荐信息