判断javascript引用类型应优先用object.prototype.tostring.call(),它返回如"[object array]"等标准字符串,兼容性好;数组专用array.isarray()更优;普通对象需排除null、数组及其他内置类型;instanceof适用于同上下文的function、date等,但跨iframe失效。

判断 JavaScript 中引用数据类型的具体种类(比如是普通对象、数组,还是 Date、RegExp 等),不能只靠 typeof,因为它对所有引用类型(除函数外)都返回 "object",甚至 null 也被误判为 "object"。要准确区分,得结合多种方法,按场景和兼容性合理选用。
用 Object.prototype.toString.call() 判断最稳妥
这是 ECMAScript 规范定义的标准方式,能获取对象内部的 [[Class]] 标签,不受跨 iframe 环境影响,兼容性好(IE6+ 支持):
-
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]"
封装成工具函数也很简单:
function getType(obj) {<br> return Object.prototype.toString.call(obj).slice(8, -1);<br>}
例如:
getType([1,2]) 返回 "Array",getType(new Set()) 返回 "Set"(ES6+)。
数组优先用 Array.isArray()
这是 ES5 标准引入的专用方法,语义清晰、性能好、且能正确处理跨 frame 的数组:
Java JDK 25 来自 OpenJDK 官方归档,版本为 JDK 25,本条下载地址已指向官方 Windows x64 zip 安装包直链,适合调试旧项目或兼容旧版 Java 运行环境。
-
Array.isArray([])→true -
Array.isArray({})→false -
Array.isArray(new window.frames[0].Array(1, 2))→true(而instanceof会失败)
现代项目中,只要目标环境支持 ES5(基本全覆盖),应无条件首选它判断数组。
普通对象需排除数组、null 和其他内置类型
仅靠 typeof obj === "object" 不够——它把数组、null、正则、日期等全包含进去了。真正“纯对象”通常指通过 {} 或 new Object() 创建的 plain object。可这样判断:
- 先确认是对象:
typeof obj === "object" && obj !== null - 再排除数组:
!Array.isArray(obj) - 最后验证构造器:
obj.constructor === Object或更安全地用Object.prototype.toString.call(obj) === "[object Object]"
注意:obj.constructor === Object 在某些继承或重写 constructor 的场景下可能不准,所以推荐搭配 toString.call 使用。
函数、Date、RegExp 等可用 instanceof 或 toString
instanceof 对这类明确有构造函数的类型很直观:
fn instanceof Functionnew Date() instanceof Date/abc/ instanceof RegExp
但它在跨 iframe 场景下会失效(因不同上下文的构造函数不相等)。如果需强兼容,仍应回到 toString.call ——它返回的字符串如 "[object Function]"、"[object Date]" 等,稳定可靠。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










