JavaScript有8种数据类型:7种原始类型(string、number、boolean、null、undefined、symbol、bigint)和1种引用类型(object);判断类型需结合typeof(快但有局限)、Object.prototype.toString.call(最精准)、Array.isArray等方法。
JavaScript 有 8 种数据类型:7 种原始类型(primitive)和 1 种引用类型(object)。判断变量类型主要靠 typeof、instanceof、Object.prototype.toString.call() 和 Array.isArray() 等方法,但每种方法都有适用边界,需结合使用。
原始类型(值类型,按值访问):
"hello"
42、3.14、NaN、Infinity
true、false
typeof null 返回 "object",属历史 bug)123n
引用类型(按引用访问):
Object 的实例,但语义和行为不同typeof 最快最常用,适合快速区分原始类型和函数,但对 null、数组、正则等返回不准确结果:
typeof "abc" → "string"
typeof 42 → "number"
typeof true → "boolean"
typeof undefined → "undefined"
typeof function(){} → "function"
typeof null → "object"(⚠️经典陷阱)typeof [] → "object"(不是 "array")typeof /[0-9]/ → "object"
typeof Symbol() → "symbol"
typeof 123n → "bigint"
这是最可靠的方式,能区分所有内置对象的具体种类:
Object.prototype.toString.call([]) → "[object Array]"
Object.prototype.toString.call({}) → "[object Object]"
Object.prototype.toString.call(new Date()) → "[object Date]"
Object.prototype.toString.call(/abc/) → "[object RegExp]"
Object.prototype.toString.call(null) → "[object Null]"
Object.prototype.toString.call(undefined) → "[object Undefined]"
Object.prototype.toString.call(new Map()) → "[object Map]"
可封装成工具函数:
const typeOf = (val) => Object.prototype.toString.call(val).slice(8, -1).toLowerCase();
typeOf([1,2]) // "array"
typeOf(new Date()) // "date"
Array.isArray(arr)(最标准、兼容好)typeof fn === "function"(简洁可靠)val === null(不能依赖 typeof)val !== null && typeof val === "object" && !Array.isArray(val)
val && typeof val.then === "function" && typeof val.catch === "function",或更稳妥地用 val instanceof Promise(注意跨 iframe 可能失效)