js中判断对象数据类型的方法大全,你想要的,这都有。

js中判断对象数据类型的方法

1.js类型判断
对js中不同数据的布尔值类型总结:false:空字符串;null;undefined;0;NaN。
true:除了上面的false的情况其他都为true;

var o = { 
          'name':'lee'
        };
var a = ['reg','blue'];
function checkBoolean(a){
         if(a){
              return true;
         }else{
              return false;
         }
 }
console.log(checkBoolean('')); //false
console.log(checkBoolean(0)); //false
console.log(checkBoolean(null)); //false
console.log(checkBoolean(undefined)); //false
console.log(checkBoolean(NaN)); //false
console.log(checkBoolean(a));//true
console.log(checkBoolean(c));//true

javascript中有六种数据类型:string;boolean;Array;Object;null;undefined。如何检测这些数据类型呢,总结方法如下:

方法一:采用typeof

  var fn = function(n){
          console.log(n);
       }
       var str = 'string';
       var arr = [1,2,3];
       var obj = {
           a:123,
           b:456
       };
       var num = 1;
       var b = true;
       var n = null;       var u = undefined;
       //方法一使用typeof方法。
       console.log(typeof str);//string
       console.log(typeof arr);//object
       console.log(typeof obj);//object
       console.log(typeof num);//number
       console.log(typeof b);//boolean
       console.log(typeof n);//null是一个空的对象
       console.log(typeof u);//undefined
       console.log(typeof fn);//function

通过上面的检测我们发现typeof检测的Array和Object的返回类型都是Object,因此用typeof是无法检测出来数组和对象的,采用方法二和方法三则可以检测出来。
方法二:instanceof

 var o = { 
           'name':'lee'
         };
 var a = ['reg','blue'];
 console.log(o instanceof Object);// true
 console.log(a instanceof Array);//  true
 console.log(o instanceof Array);//  false

方法三:使用constructor方法

var o = { 
           'name':'lee'
        };
var a = ['reg','blue'];
console.log(o.constructor == Object);//true
console.log(a.constructor == Array);//true

方法四:利用tostring()方法,这个方法是最佳的方案。

var o = { 
          'name':'lee'
        };
var a = ['reg','blue'];
function c(name,age){
         this.name = name;
         this.age = age;
 }
var c = new c('kingw','27');
console.log(Object.prototype.toString.call(a));//[object Array]
console.log(Object.prototype.toString.call(o));//[Object Object]
console.log(Object.prototype.toString.call(c));//[Object Function]
console.log(Object.prototype.toString.call(new c));//[Object Object]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值