视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
使用js判断数据类型的简单方法
2020-11-27 20:23:15 责编:小采
文档

了解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节点的判断,这些东西在我们写插件的时候都会用到。

可以封装的方法如下:


 

-->

下载本文
显示全文
专题