MDN wants to learn about developers like you: https://qsurvey.mozilla.com/s3/d6d7ff2e2f9c

Our volunteers haven't translated this article into ไทย yet. Join us and help get the job done!
You can also read the article in English (US).

The Array.isArray() function determines whether the passed value is an Array.

Array.isArray([1, 2, 3]);  // true
Array.isArray({foo: 123}); // false
Array.isArray('foobar');   // false
Array.isArray(undefined);  // false

Syntax

Array.isArray(obj)

Parameters

obj
The object to be checked.

Return value

true if the object is an Array; otherwise, false.

Description

If the object is an Array, true is returned, otherwise false is. 

See the article “Determining with absolute accuracy whether or not a JavaScript object is an array” for more details.

Examples

// all following calls return true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
// 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({ __proto__: Array.prototype });

instanceof vs isArray

When checking for Array instance, Array.isArray is preferred over instanceof because it works through 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 through iframes
arr instanceof Array; // false

Polyfill

Running the following code before any other code will create Array.isArray() if it's not natively available.

if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}

Specifications

Specification Status Comment
ECMAScript 5.1 (ECMA-262)
The definition of 'Array.isArray' in that specification.
Standard Initial definition. Implemented in JavaScript 1.8.5.
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Array.isArray' in that specification.
Standard  
ECMAScript Latest Draft (ECMA-262)
The definition of 'Array.isArray' in that specification.
Living Standard  

Browser compatibility

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic Support5 (Yes)4910.55
FeatureAndroidChrome for AndroidEdge mobileFirefox for AndroidIE mobileOpera AndroidiOS Safari
Basic Support (Yes) (Yes) (Yes)4 (Yes) (Yes) (Yes)

See also

Document Tags and Contributors

ป้ายกำกับ: 
 อัปเดตล่าสุดโดย: bel3atar,