JS中檢測數據類型的方法及封裝一個通用的方法


 
檢測數據類型1:typeof 
 
其返回結果都是字符串,字符串中包含了對應的數據類型 "number"/"string"/"boolean"/"undefined"/"symbol"/"object"/"function";
局限性:檢測null返回的是"object",檢測其他如數組、正則等特殊對象時,返回的結果都是"object",無法區分具體類型。
console.log(typeof 12); //=>"number"
console.log(typeof null); //=>"object"
console.log(typeof []); //=>"object"
console.log(typeof /^$/); //=>"object"

 

 

檢測數據類型2:instanceof
 
用於檢測某個實例是否屬於這個類,其檢測的底層機制是所有出現在其原型鏈上的類,檢測結果都是true
局限性:由於可以基於__proto__或者prototype改動原型鏈的動向,所以基於instanceof檢測出來的結果並不一定是准確的。而基本數據類型的值,連對象都不是,更沒有__proto__,雖說也是所屬類的實例,在JS中也可以調取所屬類原型上的方法,但是instanceof是不認的。
console.log(12 instanceof Number); //false
console.log(new Number(12) instanceof Number); //true
console.log([] instanceof Array); //true
console.log([] instanceof Object); //true

function Fn() {}
Fn.prototype.__proto__ = Array.prototype;
let f = new Fn();
console.log(f instanceof Array); //true

 

 

檢測數據類型3:constructor

 

這是實例所屬類原型上的屬性,指向的是類本身,但其也是可以進行修改,與instanceof類似。

let arr = [];
console.log(arr.constructor); //ƒ Array() { [native code] }
console.log(arr.constructor === Array); //true

let n=12;
console.log(n.constructor === Number); //true

 

 
檢測數據類型4:Object.prototype.toString.call([value]) / ({}).toString.call([value])
 
該方法不是用來轉換為字符串的,而是返回當前實例所屬類的信息,其返回結果的格式為"[object 所屬類信息]",即"[object Object/Array/RegExp/Date/Function/Null/Undefined/Number/String/Boolean/Symbol...]"。
這種方式基本上沒有什么局限性,是檢測數據類型相對來說最准確的方式。
console.log(Object.prototype.toString.call(12)); //[object Number]
console.log(Object.prototype.toString.call([])); //[object Array]
console.log(Object.prototype.toString.call({})); //[object Object]

function fn () {}
console.log(({}).toString.call(fn)); //[object Function]
console.log(({}).toString.call(/^$/)); //[object RegExp]
console.log(({}).toString.call(new Date)); //[object Date]

 

 

雖然檢測數據類型4相對來說最好,但格式稍微繁瑣一些,是不是可以想辦法封裝一個方法,輸出結果類似於typeof那種,直接輸出如“number”“date”“regexp”這種,確實是有的。
var class2type = {};
var toString = class2type.toString; //=>Object.prototype.toString
var hasOwn = class2type.hasOwnProperty; //=>Object.prototype.hasOwnProperty
var fnToString = hasOwn.toString; //=>Function.prototype.toString
var ObjectFunctionString = fnToString.call(Object); //=>Object.toString() =>"function Object() { [native code] }"

"Boolean Number String Function Array Date RegExp Object Error Symbol".split(" ").forEach(function anonymous(item) {
    class2type["[object " + item + "]"] = item.toLowerCase();
});
console.log(class2type);
/* [object Boolean]: "boolean"
[object Number]: "number"
[object String]: "string"
[object Function]: "function"
[object Array]: "array"
[object Date]: "date"
[object RegExp]: "regexp"
[object Object]: "object"
[object Error]: "error"
[object Symbol]: "symbol"
*/

function toType(obj) {
    //=>obj may be null / undefined
    //=>return "null"/"undefined"
    if (obj == null) {
        return obj + "";
    }

    return typeof obj === "object" || typeof obj === "function" ? class2type[toString.call(obj)] || "object" : typeof obj;
}

 

這是jQuery中用來檢測數據的方法,可以達到我們說的需求。

當然,現在公司的項目中用jQuery的已經不多了,面試會問的就更少了,但是其中的很多方法和思想還是值得我們去研究。

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM