/**
* 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"
程式碼很簡單,說明都在註解裡,這裡就不多廢話了,有相同需求的小夥伴自己來參考下吧