试一试
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
语法
js
Array.isArray(value)
参数
value-
待检查的值。
返回值
如果 value 是一个 Array,则返回 true;否则返回 false。如果 value 是一个 TypedArray 实例,则始终返回 false。
描述
Array.isArray() 检查传入的值是否是 Array。它执行一个品牌检查,类似于 in 运算符,用于检查由 Array() 构造函数初始化的私有字段。
它是 instanceof Array 的一个更健壮的替代方案,因为它避免了误报和漏报。
Array.isArray()会拒绝非实际Array实例的值,即使它们在原型链中具有Array.prototype—instanceof Array会接受这些值,因为它会检查原型链。Array.isArray()接受在另一个 Realm 中构造的Array对象 — 对于这些对象,instanceof Array会返回false,因为Array构造函数的身份在不同的 Realm 中是不同的。
有关更多详细信息,请参阅文章 "Determining with absolute accuracy whether or not a JavaScript object is an array"。
示例
使用 Array.isArray()
js
// all following calls return true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(new Array("a", "b", "c", "d"));
Array.isArray(new Array(3));
// Little known fact: Array.prototype itself is an array:
Array.isArray(Array.prototype);
// all following calls return 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));
// This is not an array, because it was not created using the
// array literal syntax or the Array constructor
Array.isArray({ __proto__: Array.prototype });
instanceof 与 Array.isArray() 的比较
在检查 Array 实例时,推荐使用 Array.isArray() 而不是 instanceof,因为它可以在不同的 Realm 中工作。
js
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]
// Correctly checking for Array
Array.isArray(arr); // true
// The prototype of arr is xArray.prototype, which is a
// different object from Array.prototype
arr instanceof Array; // false
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-array.isarray |
浏览器兼容性
加载中…