了解了 toString 的基本用法侵浸, 下面就實現(xiàn)一個全局通用的數(shù)據(jù)類型判斷方法
JavaScript 復制代碼
1? function getType(obj){
2 let type = typeof obj;
3咖祭、 if (type !== "object") { // 先進行typeof判斷, 如果是基礎數(shù)據(jù)類型, 直接返回4 return type;
5 }
6 // 對于typeof返回結果是object的供炎, 再進行如下的判斷工闺, 正則返回結果
7 return Object. prototype. toString. call(obj). replace(/^\[object(\S+)\]$/, '$1');
8 }