/** * param:o表示检测的值 * return:返回字符串"undefined"、"number"、"boolean"、"string"、"function"、"regexp"、"array"、"date"、"error"、"object"或"null" */ function typeOf(o){ var _toString = Object.prototype.toString; //获取对象的toString()方法引用 //列举基本数据类型和内置对象类型,你还可以进一步补充该数组的检测数据类型范围 var _type ={ "undefined" : "undefined", "number" : "number", "boolean" : "boolean", "string" : "string", "[object Function]" : "function", "[object RegExp]" : "regexp", "[object Array]" : "array", "[object Date]" : "date", "[object Error]" : "error" } return _type[typeof o] || _type[_toString.call(o)] || (o ? "object" : "null"); //通过把值转换为字符串,然后匹配返回字符串中是否包含特定字符进行检测 } //应用示例: var a = Math.abs; alert(typeOf(a)); //返回字符串"function"
代码很简单,说明都在注释里,这里就不多废话了,有相同需求的小伙伴自己来参考下吧