Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

Array.isArray()

BaselineWidely available

Array.isArray() 静态方法用于确定传递的值是否是一个数组

尝试一下

console.log(Array.isArray([1, 3, 5]));// Expected output: trueconsole.log(Array.isArray("[]"));// Expected output: falseconsole.log(Array.isArray(new Array(5)));// Expected output: trueconsole.log(Array.isArray(new Int16Array([15, 33])));// Expected output: false

语法

js
Array.isArray(value)

参数

value

需要检测的值。

返回值

如果valueArray,则为true;否则为false。如果valueTypedArray 实例,则总是返回false

描述

Array.isArray() 检查传递的值是否为Array。它不检查值的原型链,也不依赖于它所附加的Array 构造函数。对于使用数组字面量语法或Array 构造函数创建的任何值,它都会返回true。这使得它可以安全地使用跨领域(cross-realm)对象,其中Array 构造函数的标识是不同的,因此会导致instanceof Array 失败。

有关更多细节,请参阅文章“确定 JavaScript 对象是否为数组”

Array.isArray() 也拒绝原型链中带有Array.prototype,而实际不是数组的对象,但instanceof Array 会接受。

示例

使用 Array.isArray()

js
// 下面的函数调用都返回 trueArray.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);// 下面的函数调用都返回 falseArray.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 能跨领域工作。

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]// 正确检查 ArrayArray.isArray(arr); // true// arr 的原型是 xArray.prototype,它是一个不同于 Array.prototype 的对象arr instanceof Array; // false

规范

Specification
ECMAScript® 2026 Language Specification
# sec-array.isarray

浏览器兼容性

参见

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp