typeof对基本类型可靠但对null、数组、Date等均返回"object",核心局限性;最可靠方案是Object.prototype.toString.call(),可精确识别所有内置类型。

JavaScript 中判断数据类型,typeof 是最常用的操作符,但它对某些类型返回的结果并不准确——尤其是 对象、数组、null 和部分内置对象(如 Date、RegExp),它都统一返回 "object",这是它的核心局限性。
typeof 对基本类型基本可靠
typeof 能正确区分大部分原始类型:
-
typeof "hello"→"string" -
typeof 42→"number" -
typeof true→"boolean" -
typeof undefined→"undefined" -
typeof function() {}→"function" -
typeof Symbol()→"symbol" -
typeof BigInt(1n)→"bigint"
typeof 的主要问题:null 和对象类类型全返回 "object"
这是历史遗留 bug,但已成标准,无法更改:
-
typeof null→"object"(错误!null 是原始值) -
typeof []→"object"(无法区分数组) -
typeof {}→"object"(普通对象也这样) -
typeof new Date()→"object" -
typeof /regex/→"object" -
typeof new Map()→"object"
更可靠的替代方案:Object.prototype.toString.call()
这是目前最通用、规范的类型检测方式,能精确识别内置对象类型:
立即学习“Java免费学习笔记(深入)”;
-
Object.prototype.toString.call([])→"[object Array]" -
Object.prototype.toString.call(null)→"[object Null]" -
Object.prototype.toString.call(undefined)→"[object Undefined]" -
Object.prototype.toString.call(new Date())→"[object Date]" -
Object.prototype.toString.call(/abc/)→"[object RegExp]" -
Object.prototype.toString.call(new Set())→"[object Set]"
可封装为工具函数:
function getType(value) {
return Object.prototype.toString.call(value).slice(8, -1);
}
// getType([]) → "Array"
// getType(null) → "Null"
// getType(123) → "Number"
其他补充方法(按需选用)
针对特定场景,可结合使用:
- 判断数组:
Array.isArray(arr)(推荐,语义清晰、性能好) - 判断对象(非 null 的纯对象):
value !== null && typeof value === 'object' && !Array.isArray(value) - 判断 Promise:
value && typeof value.then === 'function'(注意不严谨,仅作简单判断) - 判断类实例:
value instanceof MyClass(仅适用于构造函数或 class)
基本上就这些。typeof 简单快,适合快速检查基本类型;真要精准识别,优先用 Object.prototype.toString.call(),再辅以 Array.isArray 等专用方法。










