試一試
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 |
瀏覽器相容性
載入中…