原理:利用JavaScript原生原型扩展函数Object.prototype.toString.call
封装:
var Type = (function() {
var type = {};
var typeArr = ['String', 'Object', 'Number', 'Array','Undefined', 'Function', 'Null', 'Symbol'];
for (var i = 0; i < typeArr.length; i++) {
(function(name) {
type['Is' + name] = function(obj) {
return Object.prototype.toString.call(obj) == '[object ' + name + ']';
}
})(typeArr[i]);
}
return type;
})();
调用:Type.Is[ 数据类型名称 ]( 需要被判断数据 ) 数据类型:'String', 'Object', 'Number', 'Array','Undefined', 'Function', 'Null', 'Symbol'
例:Type.IsFunction(function() {}) //true Type.IsObject(0) /false
参考链接:点我