在JavaScript开发过程中,我们需要经常判断变量的具体类型,才能执行对应的逻辑处理,不同的类型检查方式适用场景和判断结果存在差异,需要结合实际情况选择使用。

typeof操作符
typeof是最基础的类型检查方式,返回一个表示类型的字符串,适合判断大部分基本类型,但对引用类型的判断存在局限性。
它的使用语法非常简单,直接在变量前加上typeof即可:
// 判断基本类型
let num = 123;
let str = 'hello';
let bool = true;
let undef = undefined;
let sym = Symbol('test');
let big = 123n;
console.log(typeof num); // "number"
console.log(typeof str); // "string"
console.log(typeof bool); // "boolean"
console.log(typeof undef); // "undefined"
console.log(typeof sym); // "symbol"
console.log(typeof big); // "bigint"
// 判断引用类型的局限性
let obj = {};
let arr = [];
let func = function() {};
let nullVal = null;
console.log(typeof obj); // "object"
console.log(typeof arr); // "object",无法区分数组和普通对象
console.log(typeof func); // "function"
console.log(typeof nullVal); // "object",这是历史遗留的buginstanceof关键字
instanceof用于判断一个对象是否是某个构造函数的实例,主要用来区分不同的引用类型,它的判断逻辑是基于原型链的。
使用方式是对象 instanceof 构造函数,返回布尔值:
let arr = [];
let obj = {};
let date = new Date();
let numObj = new Number(123);
let num = 123;
console.log(arr instanceof Array); // true
console.log(arr instanceof Object); // true,数组也是Object的实例
console.log(obj instanceof Object); // true
console.log(date instanceof Date); // true
console.log(date instanceof Object); // true
console.log(numObj instanceof Number); // true
console.log(num instanceof Number); // false,基本类型不是包装对象的实例需要注意的是,instanceof只能判断引用类型,对于基本类型会直接返回false,而且如果页面存在多个全局上下文(比如iframe),不同上下文的构造函数原型链不共享,判断结果可能不符合预期。
Object.prototype.toString方法
这是通用性最强的类型检查方式,对所有类型都能返回准确的类型标识,原理是调用Object原型上的toString方法,该方法会返回包含对象类型的字符串。
使用时需要调用call或者apply改变this指向,获取目标变量的类型标识:
function getType(target) {
return Object.prototype.toString.call(target).slice(8, -1).toLowerCase();
}
let testCases = [
123,
'hello',
true,
undefined,
null,
Symbol('test'),
123n,
{},
[],
function() {},
new Date(),
new RegExp('test'),
new Map(),
new Set()
];
testCases.forEach(item => {
console.log(getType(item));
});
// 输出依次为:number, string, boolean, undefined, null, symbol, bigint, object, array, function, date, regexp, map, set这种方式可以准确区分所有内置类型,包括数组、日期、正则等引用类型,也不会出现typeof判断null为object的问题,适合需要通用类型判断的场景。
不同场景的选择建议
- 如果只需要判断基本类型(除了null),优先使用typeof,语法简单直观。
- 如果需要判断某个对象是否是特定构造函数的实例,比如判断是否是数组、是否是自定义类的实例,使用instanceof。
- 如果需要通用的类型判断,覆盖所有类型且结果准确,使用Object.prototype.toString封装的判断方法。
实际开发中可以根据需求组合使用这些方法,比如先判断是否为基本类型,再对引用类型做进一步区分,提升判断效率。
JavaScript变量类型检查typeofinstanceofObject.prototype.toString修改时间:2026-06-04 03:37:34