最直接有效的方式是用 typeof 配合 object.prototype.tostring.call() 组合判断:typeof 能准确识别基本类型(除 null 返回 "object" 外),而 tostring.call() 可精准区分所有内置类型,包括 null、数组、日期等。

最直接有效的方式是用 typeof 配合 Object.prototype.toString.call() 组合判断 —— 单靠 typeof 不够,因为它对 null 返回 "object",对数组、日期、正则等也统一返回 "object";而 toString.call() 能精准区分所有内置类型。
先看 typeof 能做什么
typeof 对基本类型识别准确(除 null 外):
typeof "abc" → "string"
typeof 42 → "number"typeof true → "boolean"typeof undefined → "undefined"typeof Symbol() → "symbol"typeof 1n → "bigint"typeof null → "object"typeof [] → "object"typeof function(){} → "function"
所以只要 typeof 返回 <code>"object" 或 "function",就不能断定它是引用类型还是基本类型(null 是基本类型但被误判),需要进一步验证。
再用 toString.call 精准识别
调用 Object.prototype.toString.call(x) 会返回形如 "[object Type]" 的字符串,其中 Type 是标准类型名:
Object.prototype.toString.call("abc") → "[object String]"Object.prototype.toString.call(42) → "[object Number]"Object.prototype.toString.call(true) → "[object Boolean]"Object.prototype.toString.call(null) → "[object Null]"Object.prototype.toString.call(undefined) → "[object Undefined]"Object.prototype.toString.call([]) → "[object Array]"Object.prototype.toString.call({}) → "[object Object]"Object.prototype.toString.call(new Date()) → "[object Date]"Object.prototype.toString.call(/a/g) → "[object RegExp]"
由此可定义一个通用判定函数:
基本类型:返回值为 "[object String]"、<code>"[object Number]"、"[object Boolean]"、"[object Undefined]"、"[object Null]"、"[object Symbol]"、"[object BigInt]"
引用类型:返回值为 "[object Object]"、"[object Array]"、"[object Function]"、"[object Date]"、"[object RegExp]"、"[object Map]"、"[object Set]" 等(所有以 "[object 开头且不是基本类型名的)
实际判断逻辑建议
可以这样写一个简洁可靠的判定函数:
function isPrimitive(value) {
const type = Object.prototype.toString.call(value);
return type === '[object String]' ||
type === '[object Number]' ||
type === '[object Boolean]' ||
type === '[object Undefined]' ||
type === '[object Null]' ||
type === '[object Symbol]' ||
type === '[object BigInt]';
}
或者更简练地利用 typeof 和 null 特例:
- 若
typeof value !== "object"→ 基本类型(含"string"、"number"等) - 若
value === null→ 基本类型 - 其余(即
typeof value === "object"且value !== null)→ 引用类型
注意:function 类型虽被 typeof 返回 "function",但它属于引用类型,所以上述逻辑中需额外处理 typeof value === "function" 的情况,统一归入引用类型。
为什么不能只靠 instanceof?
instanceof 依赖原型链,对原始值(如 "abc")永远返回 false,对 null、undefined 无法使用,且无法识别 Array 和 Object 的本质区别([] instanceof Object === true)。它适合检测自定义类实例或明确构造器关系,不适合泛类型判定。











