JavaScript数据类型有哪些_如何检测它们?

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

JavaScript数据类型有哪些_如何检测它们?-第1张图片-佛山资讯网

JavaScript 有 8 种数据类型:7 种原始类型(stringnumberbooleannullundefinedsymbolbigint)和 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免费学习笔记(深入)”;

标签: javascript java 工具

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~