判断js数据类型的函数实例详解
functionjudgeType(change){
if(arguments.length==0){
return'0';//无参数传入
}
if(change===null){
return'null'
}
if(change===undefined&&arguments.length>0){
return'undefined'
}
if(changeinstanceofFunction){
return'function'
}
if(changeinstanceofArray){
return'arry'
}
if(changeinstanceofNumber||typeofchange=='number'){
return'number'
}
if(changeinstanceofString||typeofchange=='string'){
return'string'
}
if(changeinstanceofBoolean||typeofchange=='boolean'){
return'boolean'
}
}
ps:下面看下js判断各种数据类型
了解js的都知道,有个typeof 用来判断各种数据类型,有两种写法:typeof xxx ,typeof(xxx)
如下实例:
typeof2输出number
typeofnull输出object
typeof{}输出object
typeof[]输出object
typeof(function(){})输出function
typeofundefined输出undefined
typeof'222'输出string
typeoftrue输出boolean
这里面包含了js里面的五种数据类型 number string boolean undefined object和函数类型function
看到这里你肯定会问了:我怎么去区分对象,数组和null呢?
接下来我们就用到另外一个利器:Object.prototype.toString.call
这是对象的一个原生原型扩展函数,用来更精确的区分数据类型。
我们来试试这个玩儿意儿:
vargettype=Object.prototype.toString
gettype.call('aaaa')输出[objectString]
gettype.call(2222)输出[objectNumber]
gettype.call(true)输出[objectBoolean]
gettype.call(undefined)输出[objectUndefined]
gettype.call(null)输出[objectNull]
gettype.call({})输出[objectObject]
gettype.call([])输出[objectArray]
gettype.call(function(){})输出[objectFunction]
看到这里,刚才的问题我们解决了。
constructor也能判断数据类型:
如:
''.constructor==String [].constructor==Array varobj=newObject() obj.constructor==Object
其实js里面还有好多类型判断 [objectHTMLDivElement] div对象 , [objectHTMLBodyElement] body对象 ,[objectDocument](IE)或者 [objectHTMLDocument](firefox,google)......各种dom节点的判断,这些东西在我们写插件的时候都会用到。
可以封装的方法如下 :
vargettype=Object.prototype.toString
varutility={
isObj:function(o){
returngettype.call(o)=="[objectObject]";
},
isArray:function(o){
returngettype.call(o)=="[objectArray]";
},
isNULL:function(o){
returngettype.call(o)=="[objectNull]";
},
isDocument:function(){
returngettype.call(o)=="[objectDocument]"||[objectHTMLDocument];
}
........
}
这个获取类型的方法有个简单的写法:
varType=(function(){
vartype={};
vartypeArr=['String','Object','Number','Array','Undefined','Function','Null','Symbol'];
for(vari=0;i
调用方法:Type.IsFunction(function(){}) Type.IsObject({})。。。。。
Type.Is.....
总结
以上所述是小编给大家介绍的判断js数据类型的函数实例详解,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。