typeof 返回字符串类型,能准确识别6种基础类型(undefined、boolean、number、string、symbol、bigint),但null返回"object"是历史bug;无法区分数组、日期等引用类型,需结合array.isarray()等方法。

typeof 是 JavaScript 中用于检测变量或表达式数据类型的运算符,它返回一个表示类型的字符串。它对基础数据类型(primitive types)的检测基本准确,但有几个关键细节必须注意。
能正确识别的 6 种基础类型
JavaScript 有 7 种基础数据类型(ES2020 新增 bigint),typeof 对其中 6 种返回明确且一致的结果:
-
undefined→"undefined" -
null→"object"(这是历史遗留 bug,不是基础类型检测的正常行为) -
boolean→"boolean" -
number→"number" -
string→"string" -
symbol→"symbol"(ES6 引入) -
bigint→"bigint"(ES2020 引入,现代浏览器支持)
最常踩的坑:null 的返回值
typeof null === "object" 是 JavaScript 最著名的怪异行为之一。它不代表 null 是对象,而是早期实现中的错误,被保留至今以保证向后兼容。因此:
- 不能单靠
typeof判断是否为null - 检测
null应使用严格相等:value === null - 若需统一判断“空值”,常结合使用:
value === null || value === undefined,或用value == null(利用抽象相等的特性)
typeof 对函数和对象的区分
虽然 function 不是基础类型(属于对象的一种),但 typeof 对函数有特殊处理:
-
typeof function() {}→"function" -
typeof []、typeof {}、typeof new Date()→ 全部返回"object" -
typeof /regex/→"object"(正则在某些环境中也返回"function",但规范要求是"object")
所以 typeof 无法区分普通对象、数组、日期、正则等引用类型,需要配合 Array.isArray()、instanceof 或 Object.prototype.toString.call() 进一步判断。
实用检测模式示例
下面是一个兼顾可读性与健壮性的基础类型检查片段:
function getBasicType(value) {
const t = typeof value;
if (t !== 'object') return t; // string/number/boolean/symbol/bigint/undefined/function
if (value === null) return 'null';
if (Array.isArray(value)) return 'array';
return 'object';
}
// 使用:
getBasicType(42); // "number"
getBasicType(null); // "null"
getBasicType([]); // "array"
getBasicType({}); // "object"
getBasicType(() => {}); // "function"
这个模式把 typeof 作为第一层快速过滤,再用其他方法补足它的局限性。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











