js 判断各种数据类型

了解js的都知道, 有个typeof 用来判断各种数据类型,有两种写法:typeof xxx ,typeof(xxx)

如下实例:

       typeof   2              //number
       typeof   null           //object
       typeof    undefined     //undefined
       typeof   '222'          //string
       typeof  true            //boolean

       typeof   {}             //object
       typeof    []            //object
       typeof   (function(){}) //function
这里面包含了js里面的五种基本数据类型 number string boolean null undefined和引用数据类型object

 看到这里你肯定会问了:我怎么去区分对象,数组和null呢?

 接下来我们就用到另外一个利器Object.prototype.toString.call

 这是对象的一个原生原型扩展函数,用来更精确的区分数据类型。

 我们来试试这个玩儿意儿:
        var gettype=Object.prototype.toString
        gettype.call('aaaa')           // [object String]
     或 gettype.call(new String('abc'))// [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]
 看到这里,刚才的问题我们解决了。 

 constructor也能判断数据类型,如:
           ''.constructor==String;    
           [].constructor==Array;
           var obj= new Object();
           obj.constructor==Object;
  其实js 里面还有好多类型判断

  [object HTMLDivElement]   div 对象
  [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];

          }

          ........

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值