javascript中7种基本数据类型是number、string、boolean、undefined、null、symbol、bigint;typeof可准确识别除null外的6种(返回对应小写字符串),null需用===单独判断。

直接用 typeof 就能准确判断变量是否属于基本数据类型(也叫原始类型)。
哪些是基本数据类型
JavaScript 中有 7 种基本数据类型:
-
number(包括
NaN和Infinity) - string
- boolean
- undefined
-
null(注意:
typeof null返回"object",这是个历史 bug,所以不能靠typeof判定它) - symbol
-
bigint(ES2020 新增,需用
n后缀,如123n)
typeof 正确识别为对应小写字符串;bigint 也能被正确识别为 "bigint"。
用 typeof 判断基本类型最可靠
typeof 对所有基本类型(除 null 外)返回唯一、稳定、小写的字符串:
-
typeof 42→"number" -
typeof "hi"→"string" -
typeof true→"boolean" -
typeof undefined→"undefined" -
typeof Symbol()→"symbol" -
typeof 100n→"bigint"
只要结果是这 7 个字符串之一(且不是 "object" 或 "function"),就一定是基本类型。
特别注意 null 的处理
null 是基本类型,但 typeof null === "object" 是错的。要单独判断:
- 用严格相等:
value === null - 或组合判断:
value === null || typeof value === "string"等
不要依赖 typeof 来确认 null —— 它是唯一“假 object”的基本类型。
避开常见误判
以下值虽然看起来像基本类型,但实际是对象包装器(引用类型),typeof 会返回 "object":
new String("a")new Number(42)new Boolean(true)
日常开发中应避免显式使用这些包装对象。若需区分,可用 Object.prototype.toString.call(value) 进一步验证,但对纯基本类型判断,typeof 已足够。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











