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"(⚠️错误!需额外判断)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"
日常开发中,常需区分“是否为有效值”,而非严格类型。注意:
false、0、-0、0n、""、null、undefined
!!value 可转为布尔,但会把 0、"" 等也判为 false —— 若需排除空字符串或零,应显式比较typeof x !== 'undefined',避免 ReferenceError
基本上就这些。记住核心原则:原始类型优先用 typeof(记得特判 null),复杂类型统一用 Object.prototype.toString.call(),既准确又兼容性好。
以上就是JavaScript数据类型有哪些_如何检测它们?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号