javascript tutorial - [Solved-5 Solutions] Check if object is array - javascript - java script - javascript array
Problem:
How to check if the variable is an array?
Solution 1:
The method given in the ECMAScript standard to find the class of Object is to use the toStringmethod from Object.prototype.
if( Object.prototype.toString.call( someVar ) === '[object Array]' ) {
alert( 'Array!' );
}
click below button to copy the code. By JavaScript tutorial team
Or we could use typeof to test if it is a String:
if( typeof someVar === 'string' ) {
someVar = [ someVar ];
}
click below button to copy the code. By JavaScript tutorial team
Or if you're not concerned about performance, we could just do a concat to a new empty Array.
someVar = [].concat( someVar );
click below button to copy the code. By JavaScript tutorial team
Solution 2:
We would first check if our implementation supports isArray
:
if (Array.isArray)
return Array.isArray(v);
click below button to copy the code. By JavaScript tutorial team
We could also try using the instanceof operator
v instanceof Array
click below button to copy the code. By JavaScript tutorial team
Solution 3:
jQuery also offers an $.isArray()
var a = ["A", "AA", "AAA"];
if($.isArray(a)) {
alert("a is an array!");
} else {
alert("a is not an array!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
click below button to copy the code. By JavaScript tutorial team
Solution 4:
In modern browsers we can do
Array.isArray(obj)
click below button to copy the code. By JavaScript tutorial team
- (Supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safarwe 5)
- For backward compatibility we can add the following
# only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
Array.isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
};
click below button to copy the code. By JavaScript tutorial team
- 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
Solution 5:
This is the fastest among all methods (all browsers supported):
function isArray(obj){
return !!obj && obj.constructor === Array;
}