Reputation: 271924
Array and object are the only inputs . Is there a simple function that can determine whether a variable is an array or object?
Upvotes: 1
Views: 212
Reputation: 94101
I suspect there are many other similar answers but this is one way:
if ({}.toString.call(obj) == '[object Object]') {
// is an object
}
if ({}.toString.call(obj) == '[object Array]') {
// is an array
}
This can be turned into a nifty function:
function typeOf(obj) {
return {}.toString.call(obj).match(/\w+/g)[1].toLowerCase();
}
if (typeOf(obj) == 'array') ...
This works for any type:
if (typeOf(obj) == 'date') // is a date
if (typeOf(obj) == 'number') // is a number
...
Upvotes: 3
Reputation: 123739
First check if it is an instanceof Array and then if it of object type.
if(variable instanceof Array)
{
//this is an array. This needs to the first line to be checked
//as an array instanceof Object is also true
}
else if(variable instanceof Object)
{
//it is an object
}
Upvotes: 1
Reputation: 30099
You can use Array.isArray()
:
if(Array.isArray(myVar)) {
// myVar is an array
} else {
// myVar is not an array
}
As long as you know it will be one or the other you are set. Otherwise, combine this with typeof
:
if(typeof myVar === "object") {
if(Array.isArray(myVar)) {
// myVar is an array
} else {
// myVar is a non-array object
}
}
Upvotes: 1
Reputation: 28144
(variable instanceof Array)
will return true for arrays.
You could also use variable.isArray()
, but this is not supported by older browsers.
Upvotes: 1