最可靠的方式是用 Array.isArray()——它专为判断数组设计,返回布尔值,不被原型链或跨 iframe 场景干扰;推荐首选,语义明确、行为稳定,能正确处理所有边界情况(包括跨 iframe 创建的数组)。

最可靠的方式是用 Array.isArray() —— 它专为判断数组设计,返回布尔值,不被原型链或跨 iframe 场景干扰。
推荐首选:Array.isArray()
这是 ECMAScript 5 引入的官方方法,语义明确、行为稳定,且能正确处理所有边界情况(包括跨 iframe 创建的数组)。
-
Array.isArray([])→ true -
Array.isArray({})→ false -
Array.isArray(new Array())→ true -
Array.isArray(document.querySelectorAll('div'))→ false(类数组不是数组)
次选但需谨慎:instanceof Array
它依赖构造函数和原型链,在多数单页面场景下可用,但在跨 iframe 或模块隔离环境中可能失效(因为不同上下文的 Array 构造函数不相等)。
-
[] instanceof Array→ true -
{} instanceof Array→ false - 若数组来自另一个 iframe:
iframeArr instanceof Array可能返回 false,即使它确实是数组
兼容性广但稍冗长:Object.prototype.toString.call()
该方法通过内部 [[Class]] 标签识别类型,对所有内置对象都可靠,包括跨环境场景。
立即学习“Java免费学习笔记(深入)”;
-
Object.prototype.toString.call([])→ "[object Array]" -
Object.prototype.toString.call({})→ "[object Object]" - 可封装复用:
const type = Object.prototype.toString.call(val).slice(8, -1).toLowerCase();得到"array"或"object"
不建议单独依赖:length 属性 + 其他特征
仅靠 hasOwnProperty('length') 或 typeof val === 'object' && val.length !== undefined 容易误判——类数组对象(如 arguments、NodeList)也有 length,但不是数组。
-
[1,2].hasOwnProperty('length')→ true -
document.querySelectorAll('p').hasOwnProperty('length')→ true,但它不是数组 - 必须配合其他条件(如是否具有
push、map等方法),逻辑变复杂且不可靠


















