復制代碼 代碼如下:
/**
* 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"
代碼很簡單,說明都在注釋裡,這裡就不多廢話了,有相同需求的小伙伴自己來參考下吧