typeof 能夠匹配對象的類型,可是他的能力很弱,好比 typeof new String('123')會顯示的object這是咱們不想看到的結果好久之前JQ的做者經過Object.prototype.toString.call(name)這逆天的方法幫咱們指明的道路.spa
function fixTyoeof(obj){ var retVal; //因爲typeof null 也會是object咱們這裏去排除 if(obj === null) return 'null'; //Math咱們也去排除 if(obj === Math) return 'Math'; retVal = typeof obj if(retVal === 'object'){ switch(obj.constructor){ case String: return 'string'; case Number: return 'number'; case Boolean: return 'boolean'; case Array: return 'array'; case Date: return 'date'; case RegExp: return 'regExp'; } } return retVal; }
function fixTyoeof(key){ switch(Object.prototype.toString.call(key)){ case '[object Array]' : return 'Array'; case '[object String]' : return 'String'; case '[object RegExp]' : return 'RegExp'; case '[object Number]' : return 'Number'; case '[object Function]' : return 'Function'; case '[object Boolean]' : return 'Boolean'; case '[object Math]' : return 'Math'; case '[object Date]' : return 'Date'; default : //因爲 IE678 null undefined 會顯示[object Object] 因此咱們直接匹配 switch(key){ case null : return 'Null'; case undefined : return 'Undefined'; default : return 'Object'; } } }
初版是經過 constructor 去識別,第二版是經過逆天的Object.prototype.toString.call(name)方法prototype