Object.prototype.toString
方法返回对象的类型字符串,因此可以用来判断一个值的类型。
调用方法:
Object.prototype.toString.call(value)
不同数据类型的Object.prototype.toString
方法返回值如下。
[object Number]
。[object String]
。[object Boolean]
。[object Undefined]
。[object Null]
。[object Array]
。[object Arguments]
。[object Function]
。[object Error]
。[object Date]
。[object RegExp]
。[object Object]
。也就是说,Object.prototype.toString
可以得到一个实例对象的构造函数。
Object.prototype.toString.call(2) // "[object Number]" Object.prototype.toString.call(‘‘) // "[object String]" Object.prototype.toString.call(true) // "[object Boolean]" Object.prototype.toString.call(undefined) // "[object Undefined]" Object.prototype.toString.call(null) // "[object Null]" Object.prototype.toString.call(Math) // "[object Math]" Object.prototype.toString.call({}) // "[object Object]" Object.prototype.toString.call([]) // "[object Array]"
利用这个特性,可以写出一个比typeof
运算符更准确的类型判断函数。
var type = function (o){ var s = Object.prototype.toString.call(o); return s.match(/\[object (.*?)\]/)[1].toLowerCase(); }; type({}); // "object" type([]); // "array" type(5); // "number" type(null); // "null" type(); // "undefined" type(/abcd/); // "regex" type(new Date()); // "date"
在上面这个type
函数的基础上,还可以加上专门判断某种类型数据的方法。
[‘Null‘, ‘Undefined‘, ‘Object‘, ‘Array‘, ‘String‘, ‘Number‘, ‘Boolean‘, ‘Function‘, ‘RegExp‘, ‘NaN‘, ‘Infinite‘ ].forEach(function (t) { type[‘is‘ + t] = function (o) { return type(o) === t.toLowerCase(); }; }); type.isObject({}) // true type.isNumber(NaN) // true type.isRegExp(/abc/) // true
参考:来自《JavaScript 标准参考教程(alpha)》,by 阮一峰
利用Object.prototype.toString方法,实现比typeof更准确的type校验
原文:http://www.cnblogs.com/martinl/p/6258921.html