javaScript有8种数据类型:7种原始类型(String、number、Boolean、NULL、undefined、symbol、bigint)和1种引用类型(Object);检测时应优先用typeof判断原始类型(需单独处理null),复杂类型统一用Object.prototype.toString.call()确保准确。

javascript 有 8 种数据类型:7 种原始类型(string、number、boolean、null、undefined、symbol、bigint)和 1 种引用类型(object,包括数组、函数、日期、正则、map、Set 等)。检测时不能只靠 typeof,尤其要小心 null 和数组、函数等特殊情况。
用 typeof 检测原始类型(除 null 外)
typeof 对大多数原始值表现良好,但对 null 返回 "object" 是历史遗留 bug,需单独处理。
typeof "hi" → "string"typeof 42 → "number"typeof true → "boolean"typeof undefined → "undefined"typeof Symbol() → "symbol"typeof 1n → "bigint"-
typeof null → "object"(⚠️错误!需额外判断)
准确识别 null 和 object 子类型
typeof 无法区分普通对象、数组、日期、正则等。推荐组合使用 Object.prototype.toString.call() —— 它返回标准格式的字符串标签,最可靠。
Object.prototype.toString.call(null) → "[object Null]"Object.prototype.toString.call([]) → "[object Array]"Object.prototype.toString.call(/abc/) → "[object regexp]"Object.prototype.toString.call(new date()) → "[object Date]"Object.prototype.toString.call({}) → "[object Object]"
立即学习“Java免费学习笔记(深入)”;
function getType(value) { return Object.prototype.toString.call(value).slice(8, -1); } // getType([1,2]) → "Array" // getType(null) → "Null"
检测函数与特殊对象
typeof 对函数返回 "function",这是少数例外;而 instanceof 或 constructor 易受原型链污染或跨 iframe 失效,不推荐作为主检测方式。
typeof function(){} → "function"-
typeof class C{} → "function"(类本质也是函数) getType(async () => {}) → "AsyncFunction"-
getType(new Map()) → "Map",getType(new Set()) → "Set"
快速判断真假值与存在性
日常开发中,常需区分“是否为有效值”,而非严格类型。注意:
- 假值(falsy)有 6 个:
false、0、-0、0n、""、null、undefined -
!!value可转为布尔,但会把0、""等也判为 false —— 若需排除空字符串或零,应显式比较 - 检查变量是否存在:用
typeof x !== 'undefined',避免ReferenceError
基本上就这些。记住核心原则:原始类型优先用 typeof(记得特判 null),复杂类型统一用 Object.prototype.toString.call(),既准确又兼容性好。