17370845950

JavaScript数据类型有哪些以及如何检测?
JavaScript有7种原始类型(string、number、boolean、null、undefined、symbol、bigint)和1种引用类型,检测需综合typeof、instanceof、Object.prototype.toString.call()及专用方法如Array.isArray()。

JavaScript 有 7 种原始类型(primitive types)和 1 种引用类型(object type),其中 function 是对象的特殊子类型,ArrayDateRegExp 等也属于对象,但有各自特性。检测方式需结合 typeofinstanceofObject.prototype.toString.call()Array.isArray() 等方法,不能只靠一种。

7 种原始类型及 typeof 检测结果

原始类型包括:stringnumberbooleannullundefinedsymbol(ES6)、bigint(ES2025)。它们是不可变的、按值传递的。

  • typeof "hello""string"
  • typeof 42"number"
  • typeof true"boolean"
  • typeof undefined"undefined"
  • typeof Symbol("id")"symbol"
  • typeof 123n"bigint"
  • typeof null"object"(这是历史 bug,需单独判断)

引用类型与 typeof 的局限性

typeof 对所有对象(包括数组、日期、正则、普通对象)都返回 "object",对函数返回 "function"(这是例外)。因此它无法区分不同对象类型。

  • typeof []"object"(不是 "array")
  • typeof new Date()"object"
  • typeof /abc/"object"(某些环境可能返回 "regexp",但不标准)
  • typeof function() {}"function"
  • typeof null"object"(再次强调:必须额外用 val === null 判断)

准确识别对象子类型的推荐方法

使用 Object.prototype.toString.call() 是最可靠的标准方式,它会返回形如 "[object Array]" 的字符串。

  • Object.prototype.toString.call([])"[object Array]"
  • Object.prototype.toString.call(new Date())"[object Date]"
  • Object.prototype.toString.call(/abc/)"[object RegExp]"
  • Object.prototype.toString.call({})"[object Object]"
  • Object.prototype.toString.call(null)"[object Null]"
  • Object.prototype.toString.call(undefined)"[object Undefined]"

可封装为工具函数:

function getType(val) {
  return Object.prototype.toString.call(val).slice(8, -1).toLowerCase();
}
// getType([]) → "array"
// getType(new Date()) → "date"

特殊情况的检测建议

部分类型有更简洁、语义明确的专用方法,优先使用:

  • 数组:用 Array.isArray(arr)(比 toString 更快、更直接)
  • 函数:用 typeof fn === "function"(兼容性好,且能覆盖箭头函数等)
  • NaN:用 Number.isNaN(val)(避免 isNaN("abc") 返回 true 的问题)
  • 有限数字:用 Number.isFinite(val)(排除 InfinityNaN
  • 空值判断:分开检查 val === nullval === undefined,或用 val == null(仅当允许隐式转换时)