欢迎光临亳州市华金智网
详情描述
浅析JavaScript判断变量数据类型有哪些方法

1. typeof 运算符

最常用的方法,但有一些局限性:

typeof 42;           // "number"
typeof "hello";      // "string"
typeof true;         // "boolean"
typeof undefined;    // "undefined"
typeof null;         // "object" (历史遗留问题)
typeof {};           // "object"
typeof [];           // "object" (无法区分数组)
typeof function(){}; // "function"
typeof Symbol();     // "symbol"
typeof 42n;          // "bigint"

特点

  • 对原始类型(除 null 外)判断准确
  • 无法区分数组、对象、null

2. instanceof 运算符

检查对象是否属于特定类的实例:

[] instanceof Array;      // true
{} instanceof Object;     // true
new Date() instanceof Date; // true

function Person() {}
const p = new Person();
p instanceof Person;      // true

// 局限性
"hello" instanceof String; // false(原始类型)
new String("hello") instanceof String; // true

3. Object.prototype.toString.call()

最准确的方法,可以区分所有内置类型:

Object.prototype.toString.call(42);           // "[object Number]"
Object.prototype.toString.call("hello");      // "[object String]"
Object.prototype.toString.call(true);         // "[object Boolean]"
Object.prototype.toString.call(null);         // "[object Null]"
Object.prototype.toString.call(undefined);    // "[object Undefined]"
Object.prototype.toString.call([]);           // "[object Array]"
Object.prototype.toString.call({});          // "[object Object]"
Object.prototype.toString.call(function(){});// "[object Function]"
Object.prototype.toString.call(/regex/);      // "[object RegExp]"
Object.prototype.toString.call(new Date());   // "[object Date]"

4. Array.isArray()

专门判断数组:

Array.isArray([]);      // true
Array.isArray({});      // false
Array.isArray("array"); // false

5. constructor 属性

检查对象的构造函数:

[].constructor === Array;      // true
{}.constructor === Object;     // true
"".constructor === String;      // true

// 注意:constructor 可被修改
const arr = [];
arr.constructor = Object;
arr.constructor === Array;     // false

6. Number.isNaN() 和 isNaN()

判断是否为 NaN:

Number.isNaN(NaN);       // true
Number.isNaN("NaN");     // false
isNaN("NaN");            // true(会先转换)

7. 特殊类型检查函数

// 判断是否为 null 或 undefined
function isNil(value) {
    return value == null; // == 可以匹配 null 和 undefined
}

// 判断是否为纯对象(非数组、函数等)
function isPlainObject(obj) {
    return Object.prototype.toString.call(obj) === "[object Object]";
}

// 判断是否为数字(包括数值字符串)
function isNumeric(value) {
    return !isNaN(parseFloat(value)) && isFinite(value);
}

实用工具函数示例

function getType(value) {
    // 处理 null 和 undefined
    if (value === null) return "null";
    if (value === undefined) return "undefined";

    const type = typeof value;

    // 处理对象类型
    if (type === "object" || type === "function") {
        const toString = Object.prototype.toString.call(value);
        return toString.slice(8, -1).toLowerCase();
    }

    return type;
}

// 使用示例
getType([]);          // "array"
getType(null);        // "null"
getType(new Map());   // "map"
getType(42n);         // "bigint"

总结对比

方法 优点 缺点
typeof 简单快速,适合原始类型 无法区分对象类型
instanceof 适合检查自定义类实例 不适用于原始类型,跨窗口问题
toString.call() 最准确,支持所有类型 语法较长
Array.isArray() 数组检测最佳实践 仅用于数组
constructor 直接访问构造函数 可被修改,不安全

最佳实践建议

原始类型:使用 typeof 数组:使用 Array.isArray() 精确类型判断:使用 Object.prototype.toString.call() 自定义类实例:使用 instanceof null/undefined:使用 value == null 或严格比较

选择哪种方法取决于具体场景,通常组合使用以达到最佳效果。