使用typeof檢測基本數(shù)據(jù)類型
讓我們先來看幾個使用 typeof 來判斷類型的 實例:
console.log(typeof "1"); // string
console.log(typeof 1); // number
console.log(typeof true); //boolean
console.log(typeof undefined); //undefined
console.log(typeof null);// object
console.log(typeof []); // object
console.log(typeof {}); // object
console.log(typeof window.alert); // function
從上面代碼打印的內(nèi)容來看画拾,基本數(shù)據(jù)類型(字符串嗦明、數(shù)值看政、undefined爬舰、布爾)是可以通過typeof來判斷的。
以上有一個注意點屁药,在 JavaScript 最初的實現(xiàn)中伤哺,JavaScript 中的值是由一個表示類型的標(biāo)簽和實際數(shù)據(jù)值表示的。對象的類型標(biāo)簽是 0者祖。由于 null 代表的是空指針(大多數(shù)平臺下值為 0x00)立莉,因此,null 的類型標(biāo)簽是 0七问,typeof null 也因此返回 "object"蜓耻。typeof null === 'object';
但是在實際工作中,還需要判斷時間對象(Date)械巡,數(shù)學(xué)對象(Math)等更加細(xì)致的對象刹淌,我們可以使用Object.prototype.toString()方法。
使用 toString() 檢測對象類型:
每個對象的原型都有一個 toString() 方法讥耗,當(dāng)該對象被表示為一個文本值時有勾,或者一個對象以預(yù)期的字符串方式引用時自動調(diào)用。默認(rèn)情況下古程,toString() 方法被每個 Object 對象繼承蔼卡。如果此方法在自定義對象中未被覆蓋,toString() 返回 "[object type]"挣磨,其中 type 是對象的類型雇逞。請看以下代碼
var toString = Object.prototype.toString;
console.log(toString.call(new Date)); // [object Date]
console.log(toString.call(new String));// [object String]
console.log(toString.call(Math));// [object Math]
console.log(toString.call(123));//[object Number]
console.log(toString.call(true)); //[object Boolean]
console.log(toString.call(undefined)); // [object Undefined]
console.log(toString.call(null));// [object Null]
可以通過 toString() 來獲取每個對象的類型。為了每個對象都能通過 Object.prototype.toString() 來檢測茁裙,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式來調(diào)用塘砸,傳遞要檢查的對象作為第一個參數(shù),稱為 thisArg晤锥。