前言
在編寫一些類庫中,我們經常需要判斷一些未知的用戶的輸入和配置,故而需要進行一系列的類型判斷。故而總結下JS是如何進行類型判斷的
typeof
typeof操作符返回一個字符串,表示未經計算的操作數的類型;該運算符數據類型(返回字符串,對應列表如圖)
typeof undefined = undefined
typeof Null = object
typeof Boolean = boolean
typeof Number = number
typeof String = string
typeof Symbol = symbol
typeof 函數 = function
typeof 其它對象均返回object
至此我們可以確定:Null,數組之類的對象是沒有辦法通過typeof來確定的。
instanceof
instanceof運算符用於測試構造函數的prototype屬性是否出現在對象的原型鏈中的任何位置
var str = "This is a simple string";
var num = 1111;
var boolean = true;
var und = undefined;
var nl = null;
var sb = Symbol('1111');
var obj = {}; // 非原始類型數據字面量定義
console.log(str instanceof String); // false
console.log(num instanceof Number); // false
console.log(boolean instanceof Boolean); // false
console.log(nl instanceof Object); // false
console.log(sb instanceof Symbol); // false
console.log(obj instanceof Object); // true
var strN = new String("This is a simple string");
var numN = new Number(1111);
var booleanN = new Boolean(true);
var objN = new Object();
console.log(strN instanceof String); // true
console.log(numN instanceof Number); // true
console.log(booleanN instanceof Boolean); // true
console.log(objN instanceof Object); // true
**字面量產出的原始數據類型無法使用instanceof判斷
上面兩種方法都有着各自的缺陷,那么我們應該如何確切有效的進行類型判斷呢?
下面介紹一個非常可靠的方法:
Object.propotype.toString
返回一個表示該對象的字符串
Object.prototype.toString.call('string'); //"[object String]"
Object.prototype.toString.call(1111); //"[object Number]"
Object.prototype.toString.call(true); //"[object Boolean]"
Object.prototype.toString.call(null); //"[object Null]"
Object.prototype.toString.call(undefined); //"[object Undefined]"
Object.prototype.toString.call(Symbol('111')); //"[object Symbol]"
Object.prototype.toString.call({}); //"[object Object]"