JavaScript类型判断需组合使用typeof和instanceof:typeof适用于基本类型和函数,但对null误判为"object"、无法区分引用类型;instanceof用于检测引用类型是否由某构造函数创建,但不支持原始类型且跨iframe失效;推荐优先用typeof判原始类型,Array.isArray()等专用方法或Object.prototype.toString.call()判引用类型。

JavaScript 中判断类型主要靠 typeof 和 instanceof,但它们适用场景不同、原理不同,不能互相替代。
typeof:检测基本类型和函数最直接的方式
typeof 返回一个表示数据类型的字符串(如 "string"、"number"、"function"),它在运行时通过底层类型标签快速判断,速度快、语法简单。
- 对原始类型(
string、number、boolean、undefined、symbol、bigint)返回准确结果 -
typeof null是历史 bug,返回"object"(不是对象,是空指针) -
typeof []、typeof {}、typeof new Date()都返回"object" -
typeof function() {}返回"function"(这是唯一能靠typeof准确识别的引用类型)
instanceof:判断引用类型是否由某个构造函数创建
instanceof 检查的是对象的原型链上是否存在指定构造函数的 prototype。它只适用于对象(引用类型),不适用于原始值。
-
[] instanceof Array→true -
{} instanceof Object→true -
new Date() instanceof Date→true -
"hello" instanceof String→false(字面量字符串不是String实例) -
new String("hello") instanceof String→true -
null instanceof Object或undefined instanceof Object会报错(不能对非对象使用)
为什么不能只用其中一个?
因为它们覆盖范围互补:
立即学习“Java免费学习笔记(深入)”;
-
typeof看不清对象细节:分不清Array、Date、RegExp,全都是"object" -
instanceof无法处理原始类型:对字符串、数字、布尔等字面量返回false或报错 - 跨 iframe 场景下,
instanceof可能失效(不同全局环境的Array构造函数不同) -
typeof在所有环境中行为一致,更可靠
更稳妥的类型判断建议
实际开发中,推荐组合使用或借助 Object.prototype.toString.call():
- 判断原始类型优先用
typeof - 判断具体引用类型(如数组、日期、正则)可用
Array.isArray()、value instanceof Date,或统一用: -
Object.prototype.toString.call(value)→ 返回"[object Array]"、"[object Date]"等,精准且跨 iframe 安全










