萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 型別判斷工具函式庫:isArray、isFunction、isEmpty 等完整實作

整理一組純 JS 型別判斷工具函式,涵蓋陣列、函式、物件、空值、布林、數字、字串、undefined、null、異域物件 (ActiveX/COM) 等,並提供動態載入 JS/CSS 的 $import 函式。

核心判斷函式


var is = {
    // 基礎型別
    undefined: function(a) { return typeof a === 'undefined'; },
    'null': function(a) { return a === null; }, // typeof null === 'object' 需嚴格比較
    boolean: function(a) { return typeof a === 'boolean'; },
    number: function(a) { return typeof a === 'number' && isFinite(a); },
    string: function(a) { return typeof a === 'string'; },
    function: function(a) { return typeof a === 'function'; },

    // 物件相關
    object: function(a) { return a !== null && typeof a === 'object'; },
    array: function(a) { return Array.isArray ? Array.isArray(a) : Object.prototype.toString.call(a) === '[object Array]'; },
    empty: function(o) {
        if (!is.object(o)) return true;
        for (var k in o) {
            if (Object.prototype.hasOwnProperty.call(o, k)) return false;
        }
        return true;
    },
    alien: function(a) { // 非原生 JS 物件 (ActiveX, COM, DOM 節點等)
        return is.object(a) && typeof a.constructor !== 'function';
    }
};

// 便捷別名
is.nullOrUndef = function(a) { return a == null; }; // 涵蓋 null 與 undefined

使用範例


console.log(is.array([1,2]));        // true
console.log(is.array({0:1, length:1})); // false (類陣列)
console.log(is.function(alert));     // true
console.log(is.empty({}));           // true
console.log(is.empty({a:1}));        // false
console.log(is.alien(document.body)); // true (DOM 節點)

動態載入 JS/CSS:$import


function $import(path, type, title) {
    var head = document.getElementsByTagName('head')[0];
    var exists, el;

    if (type === 'js') {
        var scripts = document.getElementsByTagName('script');
        for (var i = 0; i < scripts.length; i++) {
            if (scripts[i].src && scripts[i].src.indexOf(path) !== -1) return;
        }
        el = document.createElement('script');
        el.type = 'text/javascript';
        el.src = path;
    } else if (type === 'css') {
        var links = document.getElementsByTagName('link');
        for (var i = 0; i < links.length; i++) {
            if (links[i].href && links[i].href.indexOf(path) !== -1) return;
        }
        el = document.createElement('link');
        el.rel = 'stylesheet'; // 正式樣式表,非 alternate
        el.type = 'text/css';
        el.href = path;
        if (title) el.title = title;
    } else return;

    head.appendChild(el);
}

// 使用
$import('/js/utils.js', 'js');
$import('/css/theme.css', 'css', 'dark-theme');

改良建議

  • 使用 Object.prototype.toString.call() 統一判斷型別,避免 typeof null === 'object' 陷阱。
  • Array.isArray 為 ES5 標準,優先使用;舊環境降級至 toString 判斷。
  • $import 為同步載入,現代專案建議改用 ES Modules (import()) 或載入器 (RequireJS、SystemJS)。
  • CSS 載入建議 rel="stylesheet",alternate stylesheet 需手動啟用。
  • 可擴充 is.date、is.regexp、is.error、is.promise 等。
copyright © 萬盛學電腦網 all rights reserved