【web前端】typeof和object.toString.call()的区别



JavaScript 里使用 typeof 来判断数据类型,只能区分基本类型,即 “number”,”string”,”undefined”,”boolean”,”object” 五种。对于数组、对象来说,其关系错综复杂,使用 typeof 都会统一返回 “object” 字符串。

要想区别对象、数组单纯使用 typeof 是不行的。或者你会想到 instanceof 方法,例如下面这样:

  1. var a = {};  
  2. var b = [];  
  3. var c = function () {};  
  4.   
  5. //a b c 都是 Object 的实例  
  6. console.log(a instanceof Object) //true  
  7. console.log(b instanceof Object) //true  
  8. console.log(c instanceof Object) //true  
  9.   
  10. //只有 Array 类型的 b 才是 Array 的实例  
  11. console.log(a instanceof Array) //false  
  12. console.log(b instanceof Array) //true  
  13. console.log(c instanceof Array) //false  
  14.   
  15. //只有 Function 类型的 c 才是 Function 的实例  
  16. console.log(a instanceof Function) //false  
  17. console.log(b instanceof Function) //false  
  18. console.log(c instanceof Function) //true  

从以上代码来看,要判断复合数据类型,可以如下判断:

[javascript] view plain copy
  1. //对象  
  2. (a instanceof Object) && !(a instanceof Function) && !(a instanceof Function)  
  3. //数组  
  4. (a instanceof Object) && (a instanceof Array)  
  5. //函数  
  6. (a instanceof Object) && (a instanceof Function)  

更简便的方式,即是使用 Object.prototype.toString.call() 来确定类型,ECMA 5.1 中关于该方法的描述[1]是这样的:

When the toString method is called, the following steps are taken:
If the this value is undefined, return “[object Undefined]”.
If the this value is null, return “[object Null]”.
Let O be the result of calling ToObject passing the this value as the argument.
Let class be the value of the [[Class]] internal property of O.
Return the String value that is the result of concatenating the three Strings “[object “, class, and “]”.

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

  1. console.log(Object.prototype.toString.call(123)) //[object Number]  
  2. console.log(Object.prototype.toString.call('123')) //[object String]  
  3. console.log(Object.prototype.toString.call(undefined)) //[object Undefined]  
  4. console.log(Object.prototype.toString.call(true)) //[object Boolean]  
  5. console.log(Object.prototype.toString.call({})) //[object Object]  
  6. console.log(Object.prototype.toString.call([])) //[object Array]  
  7. console.log(Object.prototype.toString.call(function(){})) //[object Function]  

所有类型都会得到不同的字符串,几乎完美。

转自:http://mangguo.org/object-prototype-tostring-call-distinguish-between-the-type-of-object/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值