JavaScript精确判断对象类型——Object.prototype.toString

    面试中经常会问到js的数据类型有哪些,以及如何判断数据类型的问题,对于基本数据类型undefined,string,boolean,number,symbol使用最常用的typeof即可判断,但是对于null,array,{}使用typeof就会统一返回object字符串,这样就不能准确的判断。怎么解决的呢,来看下面:

首先使用typeof来判断基本的数据类型:

 //基本数据类型:number、string、boolean、null、undefined
 //引用数据类型:object(Array、Data、RegExp、function)
 alert(typeof 1);  //number;
 alert(typeof true);  //boolean;
 alert(typeof undefined);  //undefined;
 alert(typeof "hello world")   //string;

 alert(typeof {});  //object;
 alert(typeof []);  //object;
 alert(typeof null); //object,  null是一个空对象;
 alert(typeof function(){});   //function;

如上:对于null(空对象)、数组、{}(对象)使用typeof判断数据类型,都会统一返回“object”字符串


Object.prototype.toString方法精确判断

其过程简单说来就是: 
1. 获取对象的类名(对象类型)。 
2. 然后将[object、获取的对象类型的名、]组合为字符串 
3. 返回字符串 “[object Array]” 。


由于 JavaScript 中一切都是对象,任何都不例外,对所有值类型应用 Object.prototype.toString.call() 方法结果如下:

console.log(Object.prototype.toString.call(123))    //"[object Number]"
console.log(Object.prototype.toString.call('123'))    //"[object String]"
console.log(Object.prototype.toString.call(undefined))    //"[object Undefined]"
console.log(Object.prototype.toString.call(true))    //"[object Boolean]"
console.log(Object.prototype.toString.call(null))    //"[object Null]"
console.log(Object.prototype.toString.call({}))    //"[object Object]"
console.log(Object.prototype.toString.call([]))    //"[object Array]"
console.log(Object.prototype.toString.call(function(){}))    //"[object Function]"

可以看出,Object.prototype.toString可以精确的判断各种类型的数据。


判断是否为函数

 function isFunction(it) {
        return Object.prototype.toString.call(it) === '[object Function]';
    }

兼容性写法判断是否为数组

 function isArray(arr){  //自己封装的一个函数isArray(),用于判断函数传入的参数是否是数组;
      if(typeof Array.isArray === "undefined"){  //Array.isArray()是ES5中新增的方法,先判断下其是否是undefined,如果是未定义的话执行该段函数,定义一个Array.isArray()方法;
            Array.isArray = function(brr){  //如果未定义,则定义函数并传入参数;
            return Object.prototype.toString.call(brr)=="[object Array]"  //通过js中的Object.prototype.toString方法,返回一个判断,假设参数对象值属于数组内置类型,判断时,如果返回true则是数组,否则不是;
             }
       }
        return Array.isArray(arr);  //返回该方法,调用isArray()相当于调用Array.isArray();
  }

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值