如何检查JavaScript中的变量类型

126 阅读2分钟

如何检查JavaScript中的变量类型

在 JavaScript 中,检查变量类型的常用方法有以下几种,各有不同的适用场景和局限性:

1. typeof 操作符

作用:返回变量的基本类型(原始类型)。适用场景:检查原始类型(number, string, boolean, undefined, symbol, function)。局限性

  • null 返回 "object"(历史遗留问题)。
  • 对数组、对象、日期等引用类型都返回 "object"
console.log(typeof 42);          // "number"
console.log(typeof "hello");     // "string"
console.log(typeof true);        // "boolean"
console.log(typeof undefined);   // "undefined"
console.log(typeof Symbol());    // "symbol"
console.log(typeof function(){});// "function"
console.log(typeof null);        // "object"(⚠️ 陷阱)
console.log(typeof []);          // "object"
console.log(typeof {});          // "object"

2. instanceof 操作符

作用:检测对象是否是某个构造函数的实例。适用场景:检查引用类型(如 Array, Date, RegExp 等)。局限性

  • 无法检测原始类型(如 number, string)。
  • 跨窗口或 iframe 时可能失效(因为不同全局环境的构造函数不同)。
console.log([] instanceof Array);         // true
console.log({} instanceof Object);        // true
console.log(new Date() instanceof Date);  // true

// 原始类型无法检测
console.log("hello" instanceof String);   // false(需要 new String("hello"))

3. Object.prototype.toString.call()

作用:返回 [object Type] 格式的字符串,最通用的类型检测方法。 适用场景:精确检测所有类型(包括原始类型和引用类型)。

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

console.log(getType(42));           // "number"
console.log(getType("hello"));      // "string"
console.log(getType(null));         // "null"(✅ 可区分 null)
console.log(getType([]));           // "array"
console.log(getType({}));           // "object"
console.log(getType(new Date()));   // "date"
console.log(getType(/regex/));      // "regexp"
console.log(getType(Symbol()));     // "symbol"

4. 特定类型的检查方法

针对某些特殊类型,可以使用专用函数:

  • 数组Array.isArray(value)
  • NaNNumber.isNaN(value)
  • 整数Number.isInteger(value)
  • undefined:直接比较 value === undefined
  • null:直接比较 value === null
// 检查数组
console.log(Array.isArray([]));      // true

// 检查 NaN
console.log(Number.isNaN(NaN));      // true

// 检查 undefined
let x;
console.log(x === undefined);        // true

// 检查 null
let y = null;
console.log(y === null);             // true

总结

方法适用场景局限性
typeof原始类型(除null)和函数无法区分null 和对象
instanceof引用类型(如Array, Date无法检测原始类型
Object.prototype.toString所有类型(最通用)需要封装工具函数
专用方法(如Array.isArray特定类型(如数组、NaN)仅针对特定类型

推荐做法

  • 使用 Object.prototype.toString.call() 作为通用类型检查方法。
  • 对特定类型(如数组、nullundefined)使用专用方法。

更多vue相关插件及后台管理模板可访问vue admin reference,代码详情请访问github