How to check if the variable is an array?
The method given in the ECMAScript standard to find the class of Object is to use the toStringmethod from Object.prototype.
Or we could use typeof to test if it is a String:
Or if you're not concerned about performance, we could just do a concat to a new empty Array.
We would first check if our implementation supports isArray
:
We could also try using the instanceof operator
jQuery also offers an $.isArray() method:
In modern browsers we can do
- (Supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safarwe 5)
- For backward compatibility we can add the following
- If we use jQuery we can use jQuery.isArray(obj) or $.isArray(obj). If we use underscore we can use _.isArray(obj)
- If we don't need to detect arrays created in different frames we can also just use instanceof
- obj instanceof Array
This is the fastest among all methods (all browsers supported):