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 返回 "object" 是历史遗留 bug,需单独处理。
typeof "hi" → "string"typeof 42 → "number"typeof true → "boolean"typeof undefined → "undefined"typeof Symbol() → "symbol"typeof 1n → "bigint"typeof null → "object"(⚠️错误!需额外判断) 无法区分普通对象、数组、日期、正则等。推荐组合使用
typeofObject.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]"可封装成工具函数:
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"
日常开发中,常需区分“是否为有效值”,而非严格类型。注意:
false、0、-0、0n、""、null、undefined
!!value 可转为布尔,但会把 0、"" 等也判为 false —— 若需排除空字符串或零,应显式比较typeof x !== 'undefined',避免 ReferenceError
基本上就这些。记住核心原则:原始类型优先用 typeof(记得特判 null),复杂类型统一用 Object.prototype.toString.call(),既准确又兼容性好。