javaScript有7种原始类型(String、number、Boolean、NULL、undefined、symbol、bigint)和1种引用类型(Object),共8种;typeof无法准确判断null和多数对象,推荐用Object.prototype.toString.call()精准识别。

javascript 有 7 种原始(primitive)数据类型和 1 种引用(object)类型,共 8 种。准确判断变量类型不能只靠 typeof,它对 null 和多数对象都返回 "object",容易误判。
7 种原始类型 + 1 种对象类型
原始类型(按字面量直接创建,不可变,存于栈内存):
- string:如
"hello" - number:如
42、3.14、NaN、Infinity - boolean:如
true、false - null:唯一值
null(注意:typeof null === "object"是历史 bug) - undefined:未赋值或未声明变量的默认值
- symbol(es6):唯一且不可变的标识符,常用于对象属性键
- bigint(ES2020):表示任意精度整数,如
123n
引用类型(对象,存于堆内存,变量存储的是引用):
推荐的类型判断方法:Object.prototype.toString.call()
这是最可靠、可扩展的通用方式,能精准识别内置对象类型:
立即学习“Java免费学习笔记(深入)”;
-
Object.prototype.toString.call(123)→"[object Number]" -
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]"
function getType(value) { return Object.prototype.toString.call(value).slice(8, -1); } // getType([]) → "Array" // getType(Promise.resolve()) → "Promise"
按场景选择合适的方法
快速判断原始类型(排除 null/undefined):用 typeof
typeof "abc" === "string"typeof 42 === "number"-
typeof function(){} === "function"(函数是对象的特例,但typeof单独识别)
单独确认 null:用严格相等 value === null
判断数组:优先用 Array.isArray(value)(比 toString.call 更语义化、性能略优)
判断 Promise / Map / Set 等新对象:仍依赖 toString.call,因为 instanceof 在跨 iframe 场景下会失效
常见误区提醒
-
typeof null返回"object"—— 不是类型,是引擎早期 bug,已成标准,无法更改 -
typeof NaN返回"number"—— 因为NaN是一个特殊的数值 -
[] == false为true,但[]类型仍是"object"—— 类型判断和值比较无关 -
new String("a")是对象,typeof返回"object";而"a"是原始字符串 —— 字面量与构造函数创建的类型不同