主页/jQuery教程/实用函数/jQuery类型检测

jQuery类型检测

8,210字
35–52 分钟

概览

目录

在JavaScript开发中,准确判断变量的数据类型是编写健壮代码的基础。jQuery 提供了一套实用工具函数,用于简化jQuery类型检测的过程。这些方法能够帮助开发者可靠地识别各种 JavaScript 数据类型,包括函数、数组、普通对象、数字、窗口对象等,尤其是在早期JavaScript版本中类型判断机制尚不完善的时期发挥了重要作用。随着 ECMAScript 标准的演进,现代JavaScript已原生支持许多类型检测方法,但理解jQuery的这些工具函数对于维护遗留项目和深入理解语言特性依然具有价值。

基础类型检测

jQuery 提供了一系列用于检测基础数据类型的方法,它们弥补了 typeof 运算符在某些场景下的不足。这些方法都是全局工具函数,直接挂载在 jQuery 对象(即 $)上。

$.isFunction()

检测传入的参数是否为函数。该方法返回布尔值 truefalse

语法

$.isFunction( obj )

参数说明

  • obj:要检测的任意 JavaScript 对象。

示例
以下示例展示了 $.isFunction() 的多种使用场景。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>jQuery 类型检测示例:$.isFunction()</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
    <script>
        function testFunc() {}
        var arrowFunc = () => {};
        var obj = { method: function() {} };

        console.log('测试函数声明:', $.isFunction(testFunc));       // true
        console.log('测试箭头函数:', $.isFunction(arrowFunc));      // true
        console.log('测试对象方法:', $.isFunction(obj.method));     // true
        console.log('测试内置函数:', $.isFunction(Array.isArray));  // true
        console.log('测试对象:', $.isFunction(obj));                // false
        console.log('测试数组:', $.isFunction([]));                  // false
        console.log('测试字符串:', $.isFunction('string'));          // false
        console.log('测试数字:', $.isFunction(123));                 // false
    </script>
</body>
</html>

$.isArray()

检测传入的参数是否为原生数组。该方法返回布尔值。注意,在 jQuery 4.0.0 中,此方法已被移除,官方推荐使用原生的 Array.isArray()

语法

$.isArray( obj )

参数说明

  • obj:要检测的任意 JavaScript 对象。

示例
以下示例对比了 $.isArray() 与原生方法的用法,并展示了其对类数组对象的判断结果。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>jQuery 类型检测示例:$.isArray()</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
    <script>
        var arr = [1, 2, 3];
        var arrayLike = { 0: 'a', 1: 'b', length: 2 };
        var nodeList = document.querySelectorAll('div'); // 假设页面有 div 元素

        console.log('检测数组:', $.isArray(arr));                 // true
        console.log('检测类数组对象:', $.isArray(arrayLike));      // false
        console.log('检测 NodeList:', $.isArray(nodeList));        // false
        console.log('检测 arguments 对象:', (function() {
            return $.isArray(arguments);
        })());                                                     // false

        // 原生方法对比
        console.log('原生 Array.isArray(arr):', Array.isArray(arr)); // true
    </script>
</body>
</html>

数值与对象检测

除了基础类型,jQuery 还提供了针对特定对象类型的检测方法,这些方法在判断“空对象”或“窗口对象”时非常有用。

$.isNumeric()

检测传入的参数是否可被识别为数值(包括数字字符串)。该方法返回布尔值。在 jQuery 4.0.0 中,此方法已被移除,官方推荐使用更精确的原生方法组合,如 !isNaN(parseFloat(obj)) && isFinite(obj)

语法

$.isNumeric( obj )

参数说明

  • obj:要检测的任意 JavaScript 对象。

示例
以下示例展示了 $.isNumeric() 对各种值的判断结果。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>jQuery 类型检测示例:$.isNumeric()</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
    <script>
        console.log('数字 123:', $.isNumeric(123));           // true
        console.log('数字字符串 "456":', $.isNumeric('456')); // true
        console.log('浮点数 7.89:', $.isNumeric(7.89));       // true
        console.log('十六进制 0xFF:', $.isNumeric(0xFF));     // true
        console.log('无穷大 Infinity:', $.isNumeric(Infinity)); // false (jQuery 3.x 返回 false)
        console.log('NaN:', $.isNumeric(NaN));                // false
        console.log('空字符串:', $.isNumeric(''));             // false
        console.log('布尔值 true:', $.isNumeric(true));        // false
        console.log('数组:', $.isNumeric([1]));                // false
        console.log('对象:', $.isNumeric({}));                 // false
    </script>
</body>
</html>

$.isEmptyObject()

检测传入的对象是否不包含任何可枚举的自有属性。该方法返回布尔值。常用于判断一个通过 {}new Object() 创建的对象是否为空。

语法

$.isEmptyObject( obj )

参数说明

  • obj:要检测的任意 JavaScript 对象。

示例
以下示例展示了 $.isEmptyObject() 对不同对象的检测结果。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>jQuery 类型检测示例:$.isEmptyObject()</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
    <script>
        var emptyObj = {};
        var objWithProp = { name: 'test' };
        var nullObj = null;
        var dateObj = new Date();

        console.log('空对象 {}:', $.isEmptyObject(emptyObj));          // true
        console.log('带属性的对象:', $.isEmptyObject(objWithProp));    // false
        console.log('null:', $.isEmptyObject(nullObj));                // true (注意:null 被视为空)
        console.log('Date 对象:', $.isEmptyObject(dateObj));           // true (自有属性通常不可枚举)
        console.log('数组 []:', $.isEmptyObject([]));                  // true (数组索引属性不可枚举)
    </script>
</body>
</html>

$.isPlainObject()

检测传入的参数是否是一个“纯粹的对象”,即通过 {}new Object() 创建的对象,而不是由其他构造函数(如 new Date()、自定义构造函数)创建的实例。该方法返回布尔值。

语法

$.isPlainObject( obj )

参数说明

  • obj:要检测的任意 JavaScript 对象。

示例
以下示例对比了 $.isPlainObject() 对不同对象的判断。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>jQuery 类型检测示例:$.isPlainObject()</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
    <script>
        function Person(name) {
            this.name = name;
        }

        var plainObj = { key: 'value' };
        var objFromNull = Object.create(null);
        var person = new Person('John');
        var date = new Date();
        var $div = $('div'); // 假设页面有 div 元素

        console.log('字面量对象 {}:', $.isPlainObject(plainObj));          // true
        console.log('Object.create(null):', $.isPlainObject(objFromNull)); // true (部分版本)
        console.log('自定义构造实例:', $.isPlainObject(person));            // false
        console.log('Date 对象:', $.isPlainObject(date));                  // false
        console.log('jQuery 对象:', $.isPlainObject($div));                // false
        console.log('window 对象:', $.isPlainObject(window));              // false
    </script>
</body>
</html>

$.isWindow()

检测传入的参数是否为浏览器 window 对象。该方法返回布尔值。在 jQuery 4.0.0 中,此方法已被移除。

语法

$.isWindow( obj )

参数说明

  • obj:要检测的任意 JavaScript 对象。

示例
以下示例展示了 $.isWindow() 的用法。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>jQuery 类型检测示例:$.isWindow()</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
    <iframe id="testIframe" src="about:blank" style="display: none;"></iframe>
    <script>
        console.log('检测 window 对象:', $.isWindow(window));               // true
        console.log('检测 document 对象:', $.isWindow(document));           // false
        console.log('检测 iframe 的 contentWindow:', $.isWindow(document.getElementById('testIframe').contentWindow)); // true
        console.log('检测普通对象:', $.isWindow({}));                        // false
        console.log('检测函数:', $.isWindow(function(){}));                  // false
    </script>
</body>
</html>

其他辅助检测

jQuery 还提供了一些与类型检测相关的辅助工具,用于更精细的数据操作和判断。

$.type()

该方法用于检测传入参数的内置 JavaScript 类型。它返回一个字符串,表示对象的类型。与 typeof 不同,$.type() 能更清晰地区分 null、数组、日期等类型。返回的字符串可能包括 "undefined""null""boolean""number""string""function""array""date""regexp""object""error""symbol" 等。在 jQuery 4.0.0 中,此方法已被移除,官方推荐结合 typeofObject.prototype.toString.call() 来实现类似功能。

语法

$.type( obj )

参数说明

  • obj:要检测的任意 JavaScript 对象。

示例
以下示例展示了 $.type() 如何精确返回各种值的类型字符串。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>jQuery 类型检测示例:$.type()</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
    <script>
        console.log('undefined:', $.type(undefined));          // "undefined"
        console.log('null:', $.type(null));                     // "null"
        console.log('true:', $.type(true));                     // "boolean"
        console.log('123:', $.type(123));                       // "number"
        console.log('"text":', $.type('text'));                 // "string"
        console.log('function(){}:', $.type(function(){}));     // "function"
        console.log('[]:', $.type([]));                         // "array"
        console.log('new Date():', $.type(new Date()));         // "date"
        console.log('/regex/:', $.type(/regex/));               // "regexp"
        console.log('{}:', $.type({}));                         // "object"
        console.log('new Error():', $.type(new Error()));       // "error"
        console.log('Symbol():', $.type(Symbol()));             // "symbol" (如果环境支持)
    </script>
</body>
</html>

$.isXMLDoc()

检测一个 DOM 节点是否位于 XML 文档中(或本身就是 XML 文档)。该方法返回布尔值。

语法

$.isXMLDoc( node )

参数说明

  • node:要检测的 DOM 节点。

示例
以下示例展示了如何区分 HTML 和 XML 文档中的节点。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>jQuery 类型检测示例:$.isXMLDoc()</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
    <div id="htmlDiv">HTML Div</div>
    <script>
        var xmlString = '<root><person>John</person></root>';
        var xmlDoc = $.parseXML(xmlString); // 将字符串解析为 XML 文档
        var xmlElement = xmlDoc.documentElement;

        var htmlElement = document.getElementById('htmlDiv');

        console.log('HTML 文档中的 div 元素:', $.isXMLDoc(htmlElement));      // false
        console.log('HTML 文档本身:', $.isXMLDoc(document));                  // false
        console.log('XML 文档的根元素:', $.isXMLDoc(xmlElement));             // true
        console.log('XML 文档本身:', $.isXMLDoc(xmlDoc));                     // true
    </script>
</body>
</html>

版本变更记录

下表梳理了jQuery版本迭代中与类型检测相关的重要变更。

版本变更内容与影响
1.0初步引入了 $.isFunction 等基础类型检测方法。
1.2增加了 $.isArray 方法,提供跨浏览器的数组检测能力。
1.4增加了 $.isEmptyObject$.isPlainObject,增强了对对象的检测能力。
1.6增加了 $.isNumeric 方法,方便检测数值类型。
1.7改进了 $.isNumeric 的实现,使其对空字符串和空格字符串返回 false
3.0$.isNumeric 进行了调整,使其对 Infinity-Infinity 返回 false,与原生 isFinite 的行为更接近。
4.0重大变更:移除了多个已废弃的类型检测API,包括 jQuery.isArrayjQuery.isNumericjQuery.isFunctionjQuery.isWindowjQuery.type。官方推荐使用原生方法如 Array.isArray()typeofObject.prototype.toString.call() 等替代。

浏览器兼容状态

jQuery类型检测 工具函数作为 jQuery 核心库的一部分,其兼容性与 jQuery 库本身保持一致。下表列出了 jQuery 所支持的最低浏览器版本,在这些环境中,上述类型检测方法能够正常工作。

浏览器最低支持版本
Chrome30+
Edge12+
Firefox25+
Opera18+
Safari7+
Chrome Android30+
Firefox for Android25+
Opera Android18+
Safari on iOS7+
Samsung Internet4.0+
WebView Android4.4+
WebView on iOS7+

:上述版本基于jQuery 3.x系列的兼容性测试。对于更早的浏览器环境(如Internet Explorer 6-8),可以使用jQuery 1.x系列,该系列同样支持这些类型检测方法,但需要注意部分API在后续版本中行为有所调整。对于使用jQuery 4.0.0的项目,由于相关API已被移除,应迁移至原生替代方案,其兼容性取决于浏览器对 ECMAScript 5+ 特性的支持程度。