(function () {
var getProto = Object.getPrototypeOf;
var class2type = {};
var toString = class2type.toString; //Object.prototype.toString
var hasOwn = class2type.hasOwnProperty; //Object.prototype.hasOwnProperty
var fnToString = hasOwn.toString; //Function.prototype.toString
var ObjectFunctionString = fnToString.call(Object); //'function Object() { [native code] }'
// 检测是否是一个函数
var isFunction = function isFunction(obj) {
// 排除部分浏览器中 `typeof document.createElement( "object" ) === "function"` && `typeof document.getElementsByTagName("div") === "function"`
return typeof obj === "function" && typeof obj.nodeType !== "number" &&
typeof obj.item !== "function";
};
// 检测是否是window对象
var isWindow = function isWindow(obj) {
return obj != null && obj === obj.window;
};
// 检测数据类型的通用办法
var toType = function toType(obj) {
if (obj == null) return obj + "";
return /^(object|function)$/.test(typeof obj) ?
/^\[object (\w+)\]$/g.exec(toString.call(obj))[1].toLowerCase() :
typeof obj;
};
// 检测是否为数组或者类数组
var isArrayLike = function isArrayLike(obj) {
var length = !!obj && "length" in obj && obj.length,
type = toType(obj);
if (isFunction(obj) || isWindow(obj)) return false;
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && (length - 1) in obj;
};
// 检测是否为纯粹对象「纯粹对象:obj.__proto__===Object.prototype」
var isPlainObject = function isPlainObject(obj) {
var proto, Ctor;
if (toType(obj) !== "object") return false;
proto = getProto(obj);
if (!proto) return true; // Object.create(null) are plain
Ctor = hasOwn.call(proto, "constructor") && proto.constructor;
return typeof Ctor === "function" && Ctor === Object;
};
// 检测是否为空对象
var isEmptyObject = function isEmptyObject(obj) {
// Object.keys:获取对象所有非Symbol类型的私有属性「含属性名的数组集合」
// Object.getOwnPropertySymbols:获取所有Symbol类型的私有属性
var keys = Object.keys(obj);
if (typeof Symbol !== "undefined") keys = keys.concat(Object.getOwnPropertySymbols(obj));
/* // 不考虑兼容的情况下,可以直接基于ES6中的Reflect对象处理
var keys = Reflect.ownKeys(obj); */
return keys.length === 0;
};
/* 暴露API */
var utils = {
toType,
isFunction,
isWindow,
isPlainObject,
isEmptyObject,
isArrayLike
};
if (typeof window !== "undefined") window.utils = utils;
if (typeof module === "object" && typeof module.exports === "object") module.exports = utils;
})();
检测数据类型的通用办法,已封装
最新推荐文章于 2022-09-27 15:53:31 发布