js的各种数据类型判断的介绍
1.typeof
typeof用来判断各种数据类型,有两种写法:typeofxxx,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
2.instanceof
判断已知对象类型的方法.instanceof后面一定要是对象类型,并且大小写不能错,该方法适合一些条件选择或分支。
varc=[1,2,3];
vard=newDate();
vare=function(){alert(111);};
varf=function(){this.name="22";};
console.log(cinstanceofArray)//true
console.log(dinstanceofDate)//true
console.log(einstanceofFunction)//true
//console.log(finstanceoffunction)//false
3.constructor
根据对象的constructor判断,返回对创建此对象的数组函数的引用。
varc=[1,2,3];
vard=newDate();
vare=function(){alert(111);};
alert(c.constructor===Array)---------->true
alert(d.constructor===Date)----------->true
alert(e.constructor===Function)------->true
//注意:constructor在类继承时会出错
4.prototype
所有数据类型均可判断: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]
其实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];
}
........
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接