DIV CSS 佈局教程網

寫一個可靠的 JavaScript 變數型別判斷函式
編輯:關於JavaScript     

typeof 很好用,但對物件幾乎無效——除了函式之外,所有物件都只會回傳 "object"。要真正分辨 Array、Date、RegExp 這些型別,得動用一點技巧。

完整實作

// 取得 x 的型別,回傳型別名稱字串
function getType(x) {
    // 如果 x 為 null,直接回傳 "null"
    if (x == null) return "null";

    var t = typeof x;
    // 若是簡單型別,typeof 已經足夠
    if (t.toLocaleLowerCase() != "object") return t;

    // 呼叫 Object.prototype.toString 取得型別資訊
    // 它會回傳類似 "[object Array]" 的字串
    t = Object.prototype.toString.apply(x).toLowerCase();

    // 擷取其中的類名部分(去掉前面的 "[object " 與後面的 "]")
    t = t.substring(8, t.length - 1);

    if (t.toLocaleLowerCase() != "object") return t;

    // 確認 x 真的只是普通物件
    if (x.constructor == Object) return t;

    // 否則從建構子取得名稱
    if (typeof x.constructor == "function")
        return getFunctionName(x.constructor);

    return "unknow type";
}

// 取得函式名稱
function getFunctionName(fn) {
    if (typeof fn != "function") throw "the argument must be a function.";
    var reg = /\W*function\s+([\w\$]+)\s*\(/;
    var name = reg.exec(fn);
    if (!name) {
        return '(Anonymous)';   // 匿名函式
    }
    return name[1];
}

三層判斷策略

  1. 先攔 null:因為 typeof null 會誤報成 object,而 null 沒有 constructor,不先擋下來後面就會出錯。
  2. 簡單型別走 typeof:string、number、boolean、undefined、function 用 typeof 就夠準。
  3. 物件走 toString:Object.prototype.toString.call(value) 會回傳 [object Array]、[object Date] 這類字串,是最可靠的內建型別判定法。至於自訂的建構子所產生的物件,toString 只會給 [object Object],這時才需要退回用正則去解析 constructor 的函式主體。

現代寫法對照

值得一提的是,這段程式碼裡最關鍵的那一行,在今天的標準中已經有了正式意義:ES6 引入了 Symbol.toStringTag,讓物件可以自訂 toString 標記;而 Object.prototype.toString.call() 至今仍是判斷型別最穩定的方式。

如果只需要判斷是否為純物件或陣列,現在可以直接用 Array.isArray() 與 Object.prototype.toString 搭配,不必再解析 constructor 字串。不過在需要處理自訂類別、跨 iframe 物件等邊角情況時,上面這套多層降級的思路仍然值得參考。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved