Object.prototype.toString.call() 区分对象类型 typeof区分不了[] {}
分类:Javascript| 发布:camnprbubuol| 查看:781 | 发表时间:2013/4/12
在 JavaScript 里使用 typeof 来判断数据类型,只能区分基本类型,即 “number”,”string”,”undefined”,”boolean”,”object” 五种。对于数组、函数、对象来说,其关系错综复杂,使用 typeof 都会统一返回 “object” 字符串。
要想区别对象、数组、函数单纯使用 typeof 是不行的。或者你会想到 instanceof 方法,例如下面这样:

02 | var c = function () {}; |
04 | console.log(a instanceof Object); |
05 | console.log(b instanceof Object); |
06 | console.log(c instanceof Object); |
08 | console.log(a instanceof Array); |
09 | console.log(b instanceof Array); |
10 | console.log(c instanceof Array); |
12 | console.log(a instanceof Function); |
13 | console.log(b instanceof Function); |
14 | console.log(c instanceof Function); |
从以上代码来看,要判断复合数据类型,可以如下判断:
2 | (a instanceof Object) && !(a instanceof Function) && !(a instanceof Function) |
4 | (a instanceof Object) && (a instanceof Array) |
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)) |
2 | console.log(Object.prototype.toString.call( '123' )) |
3 | console.log(Object.prototype.toString.call(undefined)) |
4 | console.log(Object.prototype.toString.call( true )) |
5 | console.log(Object.prototype.toString.call({})) |
6 | console.log(Object.prototype.toString.call([])) |
7 | console.log(Object.prototype.toString.call( function (){})) |
所有类型都会得到不同的字符串,几乎完美。
由舜子写了一个通用的判断对象类型的小函数:
2 | var _t; return ((_t = typeof (o)) == "object" ? o== null && "null" || Object.prototype.toString.call(o).slice(8,-1):_t).toLowerCase(); |
执行结果:
getType("abc"); //string
getType(true); //boolean
getType(123); //number
getType([]); //array
getType({}); //object
getType(function(){}); //function
getType(new Date); //date
getType(new RegExp); //regexp
getType(Math); //math
getType(null); //null
转自:http://www.veryhuo.com/a/view/52778.html
参考地址:15.2.4.2 Object.prototype.toString ()