Array.isArray() 用于确定传递的值是否是一个 Array
。
Array.isArray([1, 2, 3]); // true Array.isArray({foo: 123}); // false Array.isArray("foobar"); // false Array.isArray(undefined); // false
语法
Array.isArray(obj)
参数
-
obj
- 需要检测的值。
返回值
如果值是 Array
,则为true; 否则为false。
描述
如果对象是 Array
,则返回true,否则为false。
有关更多详细信息,请参阅文章严格判定JavaScript对象是否为数组。
See the article “Determining with absolute accuracy whether or not a JavaScript object is an array” for more details. Given a TypedArray
instance, false
is always returned.
示例
// 下面的函数调用都返回 true Array.isArray([]); Array.isArray([1]); Array.isArray(new Array()); Array.isArray(new Array('a', 'b', 'c', 'd')) // 鲜为人知的事实:其实 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.isArray({ __proto__: Array.prototype });
instanceof
和 isArray
当检测Array实例时, Array.isArray
优于 instanceof
,因为Array.isArray能检测iframes
.
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
xArray = window.frames[window.frames.length-1].Array;
var arr = new xArray(1,2,3); // [1,2,3]
// Correctly checking for Array
Array.isArray(arr); // true
// Considered harmful, because doesn't work though iframes
arr instanceof Array; // false
Polyfill
假如不存在 Array.isArray(),则在其他代码之前运行下面的代码将创建该方法。
if (!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; }
规范
Specification | Status | Comment |
---|---|---|
ECMAScript 5.1 (ECMA-262) Array.isArray |
Standard | Initial definition. Implemented in JavaScript 1.8.5. |
ECMAScript 2015 (6th Edition, ECMA-262) Array.isArray |
Standard | |
ECMAScript Latest Draft (ECMA-262) Array.isArray |
Draft |
浏览器兼容性
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out
https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
Desktop | Mobile | Server | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
isArray |
Chrome Full support 5 | Edge Full support 12 | Firefox Full support 4 | IE Full support 9 | Opera Full support 10.5 | Safari Full support 5 | WebView Android Full support Yes | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes | nodejs Full support Yes |
Legend
- Full support
- Full support