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 是对象的特殊子类型,Array、Date、RegExp 等也属于对象,但有各自特性。检测方式需结合 typeof、instanceof、Object 和
.prototype.toString.call()Array.isArray() 等方法,不能只靠一种。
原始类型包括:string、number、boolean、null、undefined、symbol(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 对所有对象(包括数组、日期、正则、普通对象)都返回 "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"(兼容性好,且能覆盖箭头函数等)Number.isNaN(val)(避免 isNaN("abc") 返回 true 的问题)Number.isFinite(val)(排除 Infinity 和 NaN)val === null 和 val === undefined,或用 val == null(仅当允许隐式转换时)