js里面包含五种数据类型 number string boolean undefinedobject和函数类型 function
看到这里你肯定会问了:我怎么去区分对象,数组和null呢?
接下来我们就用到一个利器:Object.prototype.toString.call
这是对象的一个原生原型扩展函数,用来更精确的区分数据类型。
我们来试试这个玩儿意儿:
立即学习“Java免费学习笔记(深入)”;
var gettype=Object.prototype.toString
gettype.call('aaaa')输出 [object String]
gettype.call(2222) 输出 [object Number]
gettype.call(true) 输出 [object Boolean]
gettype.call(undefined) 输出 [object Undefined]
gettype.call(null) 输出 [object Null]
gettype.call({}) 输出 [object Object]
gettype.call([]) 输出 [object Array]
gettype.call(function(){}) 输出 [object Function]
看到这里,刚才的问题我们解决了。
其实js 里面还有好多类型判断
[object HTMLpElement] p 对象 ,
[object HTMLBodyElement] body 对象,
[object Document](IE)或者
[object HTMLDocument](firefox,google) ......
各种dom节点的判断,这些东西在我们写插件的时候都会用到。
可以封装的方法如下:
var gettype=Object.prototype.toString
var utility={
isObj:function(o){
return gettype.call(o)=="[object Object]";
},
isArray:function(o){
return gettype.call(o)=="[object Array]";
},
isNULL:function(o){
return gettype.call(o)=="[object Null]";
},
isDocument:function(){
return gettype.call(o)=="[object Document]"|| [object HTMLDocument];
}
........
}1 判断是否为数组类型
2 判断是否为字符串类型
3 判断是否为数值类型











