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()
静态方法判断传递的值是否是 Array
。
¥The Array.isArray()
static method determines whether the passed value is an Array
.
Try it
语法
参数
返回值
¥Return value
如果 value
是 Array
,则 true
;否则,false
。如果 value
是 TypedArray
实例,则始终返回 false
。
¥true
if value
is an Array
; otherwise, false
. false
is always returned if value
is a TypedArray
instance.
描述
¥Description
Array.isArray()
检查传递的值是否为 Array
。它不检查值的原型链,也不依赖于它所附加的 Array
构造函数。对于使用数组文字语法或 Array
构造函数创建的任何值,它都会返回 true
。这使得跨字段对象的使用变得安全,其中 Array
构造函数的标识不同,因此会导致 instanceof Array
失败。
¥Array.isArray()
checks if the passed value is an Array
. It does not check the value's prototype chain, nor does it rely on the Array
constructor it is attached to. It returns true
for any value that was created using the array literal syntax or the Array
constructor. This makes it safe to use with cross-realm objects, where the identity of the Array
constructor is different and would therefore cause instanceof Array
to fail.
有关更多详细信息,请参阅文章 "绝对准确地确定 JavaScript 对象是否是数组"。
¥See the article "Determining with absolute accuracy whether or not a JavaScript object is an array" for more details.
Array.isArray()
还拒绝其原型链中带有 Array.prototype
的对象,但它们不是实际的数组,而 instanceof Array
会接受。
¥Array.isArray()
also rejects objects with Array.prototype
in its prototype chain but aren't actual arrays, which instanceof Array
would accept.
示例
使用 Array.isArray()
¥Using Array.isArray()
// 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()
¥instanceof vs. Array.isArray()
检查 Array
实例时,Array.isArray()
优于 instanceof
,因为它可以跨字段工作。
¥When checking for Array
instance, Array.isArray()
is preferred over instanceof
because it works across realms.
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
规范
Specification |
---|
ECMAScript Language Specification # sec-array.isarray |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also