JavaScript 如何完美地檢查數(shù)據(jù)類型
在JavaScript中對于其8種數(shù)據(jù)類型,沒有直接且全面的檢查數(shù)據(jù)類型的內(nèi)置方法,目前知道的typeof和instanceof都不能完美解決問題。
本篇將介紹使用Object.prototype.toString如何完美解決此問題。首先我們來看看typeof 和 instanceof的缺點。
typeof操作符
typeof操作符可能是首先想到的。 它適用于number, string, undefined, boolean, symbol, function,但在使用typeof時有一些陷阱需要注意:
1、typeof null === 'object' 是一個已知的錯誤。 null不應(yīng)該是object類型。
2、它除了function,無法區(qū)分普通對象和其他內(nèi)置對象,如下示例。
typeof []; // 'object'typeof {}; // 'object'typeof new Date(); // 'object'typeof /foo/; // 'object'
instanceof操作符
instanceof操作符通過檢查對象的構(gòu)造函數(shù),來確定它是什么類型的,如下示例。
let Car = function () {};let benz = new Car();benz instanceof Car; // true
因此,instaceof雖然可以正確地確定對象的類型,但不能確定基本類型,如下示例。
[] instanceof Array // ? true(() => {}) instanceof Function; // ? truenew Map() instanceof Map; // ? true1 instanceof Number; // ? false'foo' instanceof String; // ? false
另外,由于instanceof是通過檢查對象的構(gòu)造函數(shù)判斷類型的,如果你在運行時修改了對象的原型,instanceof檢查的結(jié)果可能會改變:
const array = [];array instanceof Array; // ? trueObject.setPrototypeOf(array, null);array instanceof Array; // ? false
正如您所看到的,typeof和instanceof都不是完美的,大多數(shù)時候人們必須同時結(jié)合這兩種方法來進行類型檢查。
Object.prototype.toString方法
事實證明,在JavaScript中還有第三種更好的檢查數(shù)據(jù)類型的方法——Object.prototype.toString。
它是Object.prototype上的一個方法,結(jié)果返回一個用于描述對象的字符串值,如下示例:
Object.prototype.toString.call({}); // "[object Object]"Object.prototype.toString.call(1); // "[object Number]"Object.prototype.toString.call('1'); // "[object String]"Object.prototype.toString.call(true); // "[object Boolean]"Object.prototype.toString.call(new String('string')); // "[object String]"Object.prototype.toString.call(function () {}); // "[object Function]"Object.prototype.toString.call(null); //"[object Null]"Object.prototype.toString.call(undefined); //"[object Undefined]"Object.prototype.toString.call(/123/g); //"[object RegExp]"Object.prototype.toString.call(new Date()); //"[object Date]"Object.prototype.toString.call([]); //"[object Array]"Object.prototype.toString.call(document); //"[object HTMLDocument]"Object.prototype.toString.call(window); //"[object Window]
可以使用regexp對其返回的字符串進行一些處理,封裝一個通用的方法,適用于所有類型:
function getType(obj) { const lowerCaseTheFirstLetter = (str) => str[0].toLowerCase() + str.slice(1); // 如果是基本數(shù)據(jù)類型,直接使用typeOf操作符 const type = typeof obj; if (type !== 'object') { return type; } // 對對象類型使用 Object.prototype.toString 方法 return lowerCaseTheFirstLetter( Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1') );}getType([]); // "array"getType('123'); // "string"getType(null); // "null"getType(undefined); // "undefined"getType(); // "undefined"getType(function () {}); // "function"getType(/123/g); // "regExp"getType(new Date()); // "date"getType(new Map()); // "map"getType(new Set()); // "set"
通過 Object.prototype.toString 就能夠適用于所有數(shù)據(jù)類型的檢查。這也是大部分框架、庫中常用的方法。