JS靈巧判斷7種類型的方式

類型:

JavaScript 中有七種內置類型:
  1. 空值 (null)
  2. 未定義 (undefined)
  3. 布爾值 (boolean)
  4. 數字 (number)
  5. 字符串 (string)
  6. 對象 (object)
  7. 符號 (symbol,ES6中新增)

在 JS 中呢,有很多坑,本文章將結合 undersoce.js源碼 和我所總結的方法準確判斷這六種類型,第七種也會提供一種判斷思路;

image

先來一個小測試:

首先,大家都熟悉的一種判斷方式 typeof,這是一種雖然老掉牙但是有些實用的方式 :

typeof null         // "object"         <= 在后面文章里你會看到,巨坑!!!

typeof undefined            // "undefined"

typeof true         // "boolean"

typeof 42               // "number"

typeof "42"         // "string"

typeof {life: 42}               // "object"

typeof Symbol()             // "symbol"


// ------------后面3種是單獨提出來的注意事項------------------

typeof void 0              // "undefined"   <= 這是一個非常實用的技巧,我將在后面解釋;

typeof [1,2,3]             // "object"  <= 數組 其實也是對象,巨坑!!!

typeof function a() { }     // "function" 
image

巧用 “ ! ” 號:

!null              // true             <= 這是一個非常巧妙的技巧,下面將解釋;

!undefined         // true             <= 這是一個非常巧妙的技巧,下面將解釋;

------------我們不一樣!!!------------

!123              // false

!true             // false

!{a: 123}         // false

!function a() { }         // false

!'123'            // false

有了這個區別,我們可以做一些有趣的事情,這是在 undersoce.js 源碼里面學到的技巧,這樣能夠準確地排除 null 和 undefined

image

無敵法 “ .toString.call() ”:

當然 Object.prototype.toString.call 也可以換成 Object.prototype.toString.apply

Object.prototype.toString.call(null)        // "[object Null]"

Object.prototype.toString.call(undefined)   // "[object Undefined]"

Object.prototype.toString.call(123)         // "[object Number]"

Object.prototype.toString.call(true)        // "[object Boolean]"

Object.prototype.toString.call('123')       // "[object String]"

Object.prototype.toString.call({a: 123})    // "[object Object]"

Object.prototype.toString.call(Symbol())    // "[object Symbol]"


// ---------------單獨出來講的幾個注意事項---------------------

Object.prototype.toString.call([1,2,3]) // "[object Array]"

Object.prototype.toString.call(function a() { })    // "[object Function]" 其實函數也是object類型

Object.prototype.toString.call(new Date)    // "[object Date]"  日期對象

Object.prototype.toString.call(Math)        // [object Math]    數學函數對象

Object.prototype.toString.call(function a() { })    // "[object Function]" 其實函數也是object類型

注1:這種方式存在兼容性問題,具體兼容性問題點擊 這里 ,JavaScript 1.8.5,無法完全檢測上述情況。

注2:使用這套技巧,能夠準確地分辨這7種類型甚至更多更精確,而 typeof 卻無法區分完全!!!!!

image

來看看 " constructor "吧:

這種方式是判斷對象的構造函數是誰,至于什么是構造函數我將在另一篇文章寫道;

var n1 = null;
n.constructor             // 報錯:因為 null 是 JS 原型鏈的起點,沒有構造函數;

var u = undefined;
u.constructor             // 報錯:它也沒有構造函數;

var a = [1, 2, 3];
a.constructor === Array;   // true  數組

var n = 123;
n.constructor === Number;  // true  數字

var s1 = '123';
abc.constructor === String  // true 字符串

var o = {a: 123};
o.constructor === Object;   // true 對象

var s = Symbol()
abc.constructor === Symbol  // true 符號

------------------單獨出來講的幾個注意事項----------------------

var arr = [1, 2, 3];
arr.constructor === Array   // true 數組 能夠很好地區分

var fun = function a() { };
fun.constructor === Function  // true 函數

var abc = new Date();
abc.constructor === Date;    // true 日期 

var abc = new RegExp();
abc.constructor === RegExp; // true 正則 

var abc = Math
abc.constructor === Math;   // false 不可以像Object.prototype.toString.call()一樣區分;

abc.constructor === Object   // true 事實上沒有Math這個構造函數,Math的構造函數在 Object上的

image

最后一招 “ instanceof ”:

注意:使用對象必須是一個 object ;

// 語法: object instanceof constructor;

var n1 = 123;            // n 是類型為 Number 的元素!!!不是對象!!!
typeof n1;               // "number"    回想一下我們有7種類型
n1 instanceof Number;     // false   function Number() { }

var n2 = new Number(123)  // 現在 n2 是一個 object 元素!!!
typeof n2;               // "object"
n2 instanceof Number;     // true

正如,上述方式所說,這種方式只適合判斷 object !!!

var a = [1, 2, 3];      // 在最開始就聲明了,數組也是對象,此法可以用來判斷數組;

a instanceof Array;     // 而這個對象的構造函數是 function Array() { }

// 雖然 typeof null 也是 object 但這是最底層的元素

在這里我就不過多舉例子了,你如果不知道原型鏈的東西,那就先記住 instanceof 能判斷數組吧!!

閱讀聲明:法1都是來源于 underscore.js 源碼:

空值 (null):

法1:直接用嚴格等于判斷。
var isNull = function (obj) {
    return obj === null;
};

這是最直接并且有效的方式;

法2:巧妙地利用 ! null 的結果為 true:
var isNull = function (obj) {
    return !obj && typeof obj === "object";
};

此方法雖然很巧妙,但是沒有法1直接;

未定義 (undefined)

法1:這是最推薦的方式。
var isUndefined = function (obj) {
    return obj === void 0;
}

很多常見的工具庫都采用這種方式,極力推薦!!!;

法2:直接利用 typeof 判斷:
var isUndefined = function (obj) {
    return typeof obj === "undefined";
}

這種方式,也是相對穩定的;

注意:

  1. 在全局條件下 undefined 是不可以被修改的。
  2. 在局部條件下 undefined 在某種情況下是可以被修改的。
  3. 請狠狠地戳這里,看官方文檔解釋。
(function(undefined) {
   console.log(undefined);        // "123"
})('123')

布爾值 (boolean)

這里其實我也有疑惑,為什么 underscore.js 會這樣判斷,讀者知道可以聯系我;

var toString = Object.prototype.toString;

var isBoolean = function (obj) {
    return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
}

類似地,我們采用 .constructor 和 typeof 的方式也可以實現判斷。

數字 (number)

var toString = Object.prototype.toString;

var isNumber = function (obj) {
    return toString.call(obj) === '[object Number]';
}

類似地,我們采用 constructortypeof 的方式也可以實現判斷。

字符串 (string)

var toString = Object.prototype.toString;

var isString = function (obj) {
    return toString.call(obj) === '[object String]';
}

類似地,我們采用 constructortypeof 的方式也可以實現判斷。

對象 (object)

var toString = Object.prototype.toString;

var isObject = function (obj) {
    var type = typeof obj;
    return type === 'function' || type === 'object' && !!obj;
}

這里,是我最疑惑的地方,為什么要用 !!obj

  1. typeof null === object 結果為 true ;
  2. 最開始我已經講了一種,!obj 的方式,nullundefined 返回結果都為 true 而其他類型為 false;
  3. 以上面這種實現方式,如果傳遞值為 null 的時候,就會被 !!obj 過濾掉;

或者動手試試,將 && !!obj 刪掉,看看能否達到預期效果。

其他:

其實上文已經給出思路實現,Date, Math, RegExp等內置對象,我就不詳談了,用得較少:

數組(Array)

法1: 最穩妥的辦法:
Object.prototype.toString.call([1,2,3]) // "[object Array]"

老老實實地用這個方法吧!!!

法2:instanceof 法,僅為拓展:
var a = [1, 2, 3];      // 在最開始就聲明了,數組也是對象,此法可以用來判斷數組;

a instanceof Array;     // 而這個對象的構造函數是 function Array() { }
法3:構造函數法,僅為拓展
var a = [1, 2, 3];
a.constructor === Array;   // true  數組

注:如果 a = null ,還要報錯,這種方式堅決不推薦!!!

法4:檢查原型的構造函數,僅為拓展:
var a = [1, 2, 3];

a.__proto__.constructor === Array

其實法2-4都是屬于一種思路,判斷這個對象的構造函數是否為數組,僅僅實現方式不同罷了。

參考和鳴謝:

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容