了解js的都知道, 有个typeof 用来判断各种数据类型,有两种写法:typeof xxx ,typeof(xxx)
如下实例:
typeof 2 输出 number
typeof null 输出 object
typeof {} 输出 object
typeof [] 输出 object
typeof (function(){}) 输出 function
typeof undefined 输出 undefined
typeof '222' 输出 string
typeof true 输出 boolean
这里面包含了js里面的五种数据类型 number string boolean undefinedobject和函数类型 function
看到这里你肯定会问了:我怎么去区分对象,数组和null呢?
接下来我们就用到另外一个利器:object.prototype.tostring.call
这是对象的一个原生原型扩展函数,用来更精确的区分数据类型。
我们来试试这个玩儿意儿:
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];
}
........
}以上就是使用js 判断数据类型的简单方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号