Array.isArray() 能正确识别跨 iframe 数组,而 instanceof Array 不能——因前者检查内部属性[[Class]],后者依赖当前上下文的原型链;iframe 拥有独立全局环境,其 Array.prototype 与主页面不相等,导致 instanceof 失效。

Array.isArray() 能正确识别跨 iframe 创建的数组,而 instanceof Array 在这种场景下大概率返回 false——根本原因在于两者判断机制不同:一个看“本质”,一个看“出身”。
判定逻辑完全不同
Array.isArray() 是语言层内置的类型检测方法,它不依赖原型链,而是直接检查值的内部属性 [[Class]](或 ES6+ 的 [[TypedArray]] 等标识),只要该值是规范定义的数组,就返回 true。
instanceof Array 则是运行时行为:它沿着对象的 __proto__ 链向上查找,看能否找到 Array.prototype。但这个 Array.prototype 必须是当前执行上下文(即当前 window)中的那个,而不是 iframe 里的。
iframe 中的 Array 是“另一个世界”的构造函数
每个 iframe 拥有独立的全局环境,包括独立的 window、Array、Date 等内置构造函数。它们虽然名字一样、行为一致,但内存地址不同,原型链互不相通。
例如:
- 主页面的
Array.prototype !== iframe.contentWindow.Array.prototype - iframe 里用
new Array(1,2)创建的数组,其__proto__指向的是 iframe 内部的Array.prototype - 这个原型不在主页面的原型链上 →
arr instanceof Array返回false
实际代码表现
假设 iframe 已加载完成:
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);
const iframeArray = iframe.contentWindow.Array;
const arr = new iframeArray(1, 2, 3);
console.log(arr instanceof Array); // false(主页面 Array)
console.log(arr instanceof iframeArray); // true(同环境才成立)
console.log(Array.isArray(arr)); // true(跨环境也成立)
注意:arr instanceof iframe.contentWindow.Array 才为 true,但这要求你提前拿到 iframe 的构造函数,实际开发中往往不可控或不方便。
为什么不能只靠 instanceof?
除了 iframe 场景,以下情况 instanceof Array 同样失效:
-
Array.prototype本身(Array.prototype instanceof Array === false) - 被篡改过原型的对象(如
Object.setPrototypeOf({}, Array.prototype)会误判为数组) - 通过
Object.create(Array.prototype)创建的对象(不是数组,但instanceof Array为true)
而 Array.isArray() 对这些边界情况都有明确定义,结果稳定可靠。










