DIV CSS 佈局教程網

JavaScript 自定義函數判斷變量類型的實現
編輯:關於JavaScript     

日常我們習慣用 typeof 判斷 JS 變量的類型,但很多時候僅靠 typeof 是不夠的——最典型的就是 typeof [] 返回 "object",typeof null 也返回 "object",無法區分真實類型。

下面這個自定義函數把判斷做得更全面一些:

function varType(v) {
    if (typeof v === "object") {
        if (v === null) return 'null';

        // 通過 constructor 推斷具體類型
        if (v.constructor) {
            return (v.constructor.toString()).match(/(\?: )[\w\/$]+/)[0];
        }

        // 老 IE 的兜底方案:借助 VBScript 的 TypeName
        if (typeof typeof2 === 'undefined' && window.execScript) {
            window.execScript(
                'Function vbsTypeName(o):vbsTypeName=TypeName(o):End Function',
                'vbscript'
            );
            window.execScript('function typeof2(o){return vbsTypeName(o)}', 'jscript');
        }
        if (typeof typeof2 !== 'undefined') {
            return typeof2(v);
        }
        return "object";
    }
    return typeof v;
}

普通常量與原生對象

這一類在各瀏覽器上的結果基本一致:

alert(varType());              // undefined
alert(varType(100));           // number
alert(varType({}));            // Object
alert(varType([]));            // Array
alert(varType(/ /));           // RegExp
alert(varType(new Date()));    // Date
alert(varType(Date));          // function
alert(varType(Object));        // function
alert(varType(RegExp));        // function

DOM 與宿主對象

這一類在不同瀏覽器上返回值會有差異:

alert(varType(window));          // IE: HTMLWindow2   FF: Window
alert(varType(document));        // IE: HTMLDocument  FF: HTMLDocument
alert(varType(document.body));   // IE: HTMLBody      FF: HTMLBodyElement
alert(varType(Option));          // IE: Object        FF: function
alert(varType(Image));           // IE: Object        FF: function
alert(varType(navigator));       // IE: DispHTMLNavigator  FF: Navigator

// 以下幾個僅 IE 支持
alert(varType(ActiveXObject));   // IE: function
alert(varType(Enumerator));      // IE: function
alert(varType(new ActiveXObject("Scripting.Dictionary")));  // IE: Dictionary
alert(varType(new Enumerator()));// IE: Enumerator

更實用的現代寫法

值得一提的是,如今更推薦用 Object.prototype.toString.call() 來做類型判斷,它幾乎能覆蓋所有內建類型且結果穩定:

function typeOf(value) {
    return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}

typeOf([]);        // "array"
typeOf(null);      // "null"
typeOf(new Date()); // "date"
typeOf(/x/);       // "regexp"

更多關於 JavaScript 的內容感興趣的讀者,可查看本站專題:《JavaScript 數學運算用法總結》、《JavaScript 查找算法技巧總結》、《JavaScript 錯誤與調試技巧總結》、《JavaScript 數據結構與算法技巧總結》及《JavaScript 遍歷算法與技巧總結》。

希望本文所述對大家理解 JavaScript 的類型判斷有所幫助。

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