Array.isArray()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Array.isArray()
静态方法用于确定传递的值是否是一个数组。
尝试一下
console.log(Array.isArray([1, 3, 5]));
// Expected output: true
console.log(Array.isArray("[]"));
// Expected output: false
console.log(Array.isArray(new Array(5)));
// Expected output: true
console.log(Array.isArray(new Int16Array([15, 33])));
// Expected output: false
语法
Array.isArray(value)
参数
value
-
需要检测的值。
返回值
如果 value
是 Array
,则为 true
;否则为 false
。如果 value
是 TypedArray
实例,则总是返回 false
。
描述
Array.isArray()
检查传递的值是否为 Array
。它不检查值的原型链,也不依赖于它所附加的 Array
构造函数。对于使用数组字面量语法或 Array
构造函数创建的任何值,它都会返回 true
。这使得它可以安全地使用跨领域(cross-realm)对象,其中 Array
构造函数的标识是不同的,因此会导致 instanceof Array
失败。
有关更多细节,请参阅文章“确定 JavaScript 对象是否为数组”。
Array.isArray()
也拒绝原型链中带有 Array.prototype
,而实际不是数组的对象,但 instanceof Array
会接受。
示例
使用 Array.isArray()
// 下面的函数调用都返回 true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(new Array("a", "b", "c", "d"));
Array.isArray(new Array(3));
// 鲜为人知的事实:其实 Array.prototype 也是一个数组:
Array.isArray(Array.prototype);
// 下面的函数调用都返回 false
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray("Array");
Array.isArray(true);
Array.isArray(false);
Array.isArray(new Uint8Array(32));
// 这不是一个数组,因为它不是使用数组字面量语法或 Array 构造函数创建的
Array.isArray({ __proto__: Array.prototype });
instanceof 和 Array.isArray()
当检测 Array
实例时,Array.isArray
优于 instanceof
,因为 Array.isArray
能跨领域工作。
const iframe = document.createElement("iframe");
document.body.appendChild(iframe);
const xArray = window.frames[window.frames.length - 1].Array;
const arr = new xArray(1, 2, 3); // [1, 2, 3]
// 正确检查 Array
Array.isArray(arr); // true
// arr 的原型是 xArray.prototype,它是一个不同于 Array.prototype 的对象
arr instanceof Array; // false
规范
Specification |
---|
ECMAScript® 2025 Language Specification # sec-array.isarray |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
isArray |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support