js 检测数据类型instanceof/constructor和 Object.prototype.toString.call()

1、检测字符串、数值、布尔值、undefined、function 使用typeof(在Safari和Chrome中检测正则也会返回 "function")

检测是否为数字用 isNaN()

2、检测null 应用“===”

3、检测其它对象:

      方法一:利用instanceof/constructor  

      (再某些ie版本中存在跨iframe问题,每个iframe下都有自己的一套原型链,跨frame实例化的对象彼此是不共享原型链)

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. alert(A  instanceof  Object)  
  2. alert(A  instanceof  Array)  
  3. alert(A  instanceof  RegExp)    
  4. alert(A.constructor==Array)  
      例如:

      方法二:利用 Object.prototype.toString.call()  

      (解决了方法一跨iframe 失效的问题)

      例如:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Object.prototype.toString.call ({})          //"[objectObject]"  
  2. Object.prototype.toString.call ([1,2,3,4]);  //"[objectArray]"  
  3. Object.prototype.toString.call(newDate());   //"[objectDate]"  
  4. Object.prototype.toString.call(/^hello/);    //"[objectRegExp]"  
  5. Object.prototype.toString.call(newError())   //"[objectError]"  
  6. Object.prototype.toString.call(newNumber())  //"[objectNumber]"  

      参考jquery解决方案

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. var class2type = {};  
  2. $.each("Boolean Number String Function Array Date RegExp Object".split(" "), function (i, name) {  
  3.     class2type[ "[object " + name + "]" ] = name.toLowerCase();  
  4. });  
  5. $.type = function (obj) {  
  6.     return obj == null ?  
  7.         String(obj) : class2type[ toString.call(obj) ] || "object"  
  8. };  

       另外,ECMAScript 5 定义了一个新方法Array.isArray(),该函数在参数为数组时返回true,例如

       Array.isArray([])     // true

       所以我们可以定义:  

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. if(typeof Array.isArray=="undefined"){  
  2.    Array.isArray=function(obj){  
  3.        return Object.prototype.toString.call(obj)==="[object Array]";  
  4.    }  
  5. }  

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值