I would like to check whether a variable is either an array or a single value in JavaScript.
I have found a possible solution...
if (variable.constructor == Array)...
Is this the best way this can be done?
I would like to check whether a variable is either an array or a single value in JavaScript.
I have found a possible solution...
if (variable.constructor == Array)...
Is this the best way this can be done?
You could also use:
if (value instanceof Array) {
alert('value is Array!');
} else {
alert('Not an array');
}
This seems to me a pretty elegant solution, but to each his own.
Via Crockford:
function typeOf(value) {
var s = typeof value;
if (s === 'object') {
if (value) {
if (value instanceof Array) {
s = 'array';
}
} else {
s = 'null';
}
}
return s;
}
The main failing Crockford mentions is an inability to correctly determine arrays that were created in a different context, e.g., window
.
That page has a much more sophisticated version if this is insufficient.
There are multiple solutions with all their on quirks. This page gives a good overview. One possible solution is:
function isArray(o) {
return Object.prototype.toString.call(o) === '[object Array]';
}
I noticed someone mentioned about JQuery, but I didn't know there was an isArray()
function. It turns out it was added in version 1.3.
JQuery implements it as Peter suggests...
isArray: function( obj ) {
return toString.call(obj) === "[object Array]";
},
Having put a lot of faith in JQuery already (especially their techniques for cross-browser compatibility) I will either upgrade to version 1.3 and use their function (providing that upgrading doesn’t cause too many problems) or use this suggested method directly in my code.
Many thanks for the suggestions.