Detect if parameter passed is an array? Javascript [duplicate]
Solution 1:
if (param instanceof Array)
...
Edit. As of 2016, there is a ready-built method that catches more corner cases, Array.isArray
, used as follows:
if (Array.isArray(param))
...
Solution 2:
This is the approach jQuery 1.4.2 uses:
var toString = param.prototype.toString;
var isArray = function(obj) {
return toString.call(obj) === "[object Array]";
}
Solution 3:
I found this here:
function isArray(obj) {
return obj.constructor == Array;
}
also this one
function isArray(obj) {
return (obj.constructor.toString().indexOf(”Array”) != -1);
}
Solution 4:
You can test the constructor
property:
if (param.constructor == Array) {
...
}
Though this will include objects that have an array prototype,
function Stack() {
}
Stack.prototype = [];
unless they also define constructor:
Stack.prototype.constructor = Stack;
or:
function Stack() {
this.constructor = Stack;
}
Solution 5:
Some days ago I was building a simple type detection function, maybe its useful for you:
Usage:
//...
if (typeString(obj) == 'array') {
//..
}
Implementation:
function typeString(o) {
if (typeof o != 'object')
return typeof o;
if (o === null)
return "null";
//object, array, function, date, regexp, string, number, boolean, error
var internalClass = Object.prototype.toString.call(o)
.match(/\[object\s(\w+)\]/)[1];
return internalClass.toLowerCase();
}
The second variant of this function is more strict, because it returns only object types described in the ECMAScript specification (possible output values: "object"
, "undefined"
, "null"
, and "function"
, "array"
, "date"
, "regexp"
, "string"
, "number"
, "boolean"
"error"
, using the [[Class]]
internal property).