typeof 对 null 返回 "object"(历史 bug),对数组、普通对象、正则、日期等均返回 "object",仅对函数返回 "function";instanceof 依赖原型链,跨 iframe 失效且无法检测原始值。

typeof 适合快速判断基本类型,但对 null 和对象(包括数组、正则、日期等)一律返回 "object";instanceof 可识别引用类型的构造器来源,但依赖原型链,跨 iframe 失效。
typeof 对哪些值返回意外结果?
它在几个关键地方“不准”:
-
typeof null返回"object"(历史 bug,已成标准) -
typeof []、typeof {}、typeof /reg/、typeof new Date()全是"object" -
typeof function() {}返回"function"(这是特例,不是标准对象) -
typeof Symbol()返回"symbol",typeof BigInt(1)返回"bigint"(ES6+ 新增,表现正常)
instanceof 的原理和典型失效场景
它本质是检查 left.__proto__ 是否沿原型链能找到 right.prototype。因此:
- 能正确区分
[] instanceof Array(true)、{} instanceof Object(true)、/a/ instanceof RegExp(true) - 但
let iframe = document.createElement('iframe'); document.body.appendChild(iframe); let arr = iframe.contentWindow.Array; [] instanceof arr返回false(不同全局环境,原型链断裂) - 无法检测原始值:
123 instanceof Number是false(数字字面量不是实例)
更可靠的类型检测方案(推荐组合)
单靠一个操作符不够,常用补救方式:
立即学习“Java免费学习笔记(深入)”;
- 判空先用
value === null,再用typeof value === "object"避开null陷阱 - 检测数组优先用
Array.isArray(value)(最准,ES5+ 支持) - 检测内置对象统一走
Object.prototype.toString.call(value):
Object.prototype.toString.call([]) // "[object Array]"
Object.prototype.toString.call(/a/) // "[object RegExp]"
Object.prototype.toString.call(null) // "[object Null]" - 自定义类可用
instanceof,但注意避免跨上下文使用
真正难的不是记住区别,而是意识到:JavaScript 没有“类型系统”的强契约,所有检测都是基于运行时结构的推测——所以别依赖单一手段,尤其在处理第三方数据或跨环境对象时。











