调用Object.prototype.toString方法。使用call方法,可以在任意值上调用Object.prototype.toString方法,从而帮助我们判断这个值的类型。不同数据类型的toString方法返回值如下:
- 数值:返回[object Number]
- 字符串:返回[object String]
- 布尔值:返回[object Boolean]
- undefined:返回[object Undefined]
- null:返回[object Null]
- 对象:返回"[object " + 构造函数的名称 + “]”
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]"
自定义一个type函数方法 返回数据类型
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',
'Element',
'NaN',
'Infinite'
].forEach(function (t) {
type['is' + t] = function (o) {
return type(o) === t.toLowerCase();
};
});
type.isObject({}); // true
type.isNumber(NaN); // false
type.isElement(document.createElement('div')); // true
type.isRegExp(/abc/); // true
欢迎关注技术开发分享录:http://fenxianglu.cn/