js类型判断

之前遇到过一个面试题需要判断出是字符串还是数字的一个问题,

后来想了一下,typeof() 还可以做到,但是typeof()不是万能的,判断不出来数组和对象的区别,我自己封装了一个简单的类型判断的方法,记录一下,以后用到了可以直接拿走就用的;

 
它可以判断类型具体的是,array || object || function || boolean || null || string || number   这几个类型中的那一个,

function isType(obj){
va    r type = typeof(obj);
if(type!=='object'){
return type;
}else if(!obj){
return 'null';
}else if(Array.isArray(obj)===true){
return 'array';
}else{
return type;
}

}

也可以在传参时再传一个用来判断也是不错的;

function isType(obj,str){
var type = typeof(obj);
if(!obj){
type = 'null';
}else if(Array.isArray(obj)===true){
type = 'array';
}
if(str&&str===type){
return true;
}else if(str&&!str===type){
return false;
}
return type;

}

即可以达到判断类型的效果,又可以直接对比

猜你喜欢

转载自www.cnblogs.com/boomBoy/p/9013580.html